亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python:從函數返回異常

python:從函數返回異常

蠱毒傳說 2021-06-06 08:46:54
假設我有以下功能:def test():  ...  if x['error']:    raise無論是否x['error']定義,這都會引發異常。相反,如果我嘗試這個,它不會拋出任何異常:def test():  ...  try:    if x['error']:      raise  except:    return如何測試特定值并在定義時返回異常,如果未定義則成功返回?
查看完整描述

3 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

def test():

  ...

  if x.get(‘error’):

    raise

您可以使用字典的內置get函數避免無意中引發錯誤。None如果指定鍵處的值不存在,則Get 將返回而不是拋出異常。


查看完整回答
反對 回復 2021-06-09
?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

如果要將錯誤作為字符串返回:


>>> def test():

    try:

        if x['error']:raise

    except Exception as err:

        return err


>>> test()

NameError("name 'x' is not defined",)

如果要發生錯誤:


>>> def test():

    try:

        if x['error']:raise

    except:

        raise


>>> test()

Traceback (most recent call last):

  File "<pyshell#20>", line 1, in <module>

    test()

  File "<pyshell#19>", line 3, in test

    if x['error']:raise

NameError: name 'x' is not defined


查看完整回答
反對 回復 2021-06-09
?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

試試這個


def check_not_exist(d,k):

   #if keys exists in dict,raise it

   if k in d:

     raise

   else:

     return True


查看完整回答
反對 回復 2021-06-09
  • 3 回答
  • 0 關注
  • 271 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號