如何在Python中引發異常,以便以後可以通過
except
塊捕獲該異常?
#1樓
不要這樣做 。 引發一個絕對的 Exception
絕對不是正确的選擇。 請參閱亞倫·霍爾(Aaron Hall)的出色答案 。
不能得到比這更多的pythonic:
raise Exception("I know python!")
如果您需要更多資訊,請參閱python 的凸起語句文檔 。
#2樓
如何在Python中手動引發/引發異常?
使用在語義上适合您的問題的最特定的Exception構造函數 。
在您的消息中要具體,例如:
raise ValueError('A very specific bad thing happened.')
不要引發通用異常
避免引發通用異常。 要捕獲它,您必須捕獲将其子類化的所有其他更具體的異常。
問題1:隐藏錯誤
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
例如:
def demo_bad_catch():
try:
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)
問題2:無法抓住
而更具體的捕獲不會捕獲一般異常:
def demo_no_catch():
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>>> demo_no_catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
最佳做法: raise
聲明
raise
而是使用在語義上适合您的issue的最特定的Exception構造函數 。
raise ValueError('A very specific bad thing happened')
這也友善地允許将任意數量的參數傳遞給構造函數:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
這些參數由Exception對象上的
args
屬性通路。 例如:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
版畫
('message', 'foo', 'bar', 'baz')
在Python 2.5中,實際的
message
屬性已添加到BaseException中,以鼓勵使用者繼承Exceptions的子類并停止使用
args
,但是
message
的引入和args的原始棄用已被收回 。
最佳做法: except
子句
except
例如,在except子句中時,您可能想要記錄發生了特定類型的錯誤,然後重新引發。 保留堆棧跟蹤時執行此操作的最佳方法是使用裸機擡高語句。 例如:
logger = logging.getLogger(__name__)
try:
do_something_in_app_that_breaks_easily()
except AppError as error:
logger.error(error)
raise # just this!
# raise AppError # Don't do this, you'll lose the stack trace!
不要修改您的錯誤...但是如果您堅持的話。
您可以使用
sys.exc_info()
來保留stacktrace(和錯誤值),但這是更容易出錯的方式,并且在Python 2和3之間存在相容性問題 ,建議您使用裸
raise
來重新籌集資金。
解釋一下
sys.exc_info()
傳回類型,值和回溯。
type, value, traceback = sys.exc_info()
這是Python 2中的文法-請注意,這與Python 3不相容:
raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
如果願意,您可以修改新加薪時發生的情況-例如,為執行個體設定新的參數:
def error():
raise ValueError('oops!')
def catch_error_modify_message():
try:
error()
except ValueError:
error_type, error_instance, traceback = sys.exc_info()
error_instance.args = (error_instance.args[0] + ' <modification>',)
raise error_type, error_instance, traceback
并且我們在修改args時保留了整個回溯。 請注意,這不是最佳做法,并且在Python 3中是無效的文法 (使得保持相容性變得更加困難)。
>>> catch_error_modify_message()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch_error_modify_message
File "<stdin>", line 2, in error
ValueError: oops! <modification>
在Python 3中 :
raise error.with_traceback(sys.exc_info()[2])
同樣:避免手動操作回溯。 它效率較低 ,更容易出錯。 而且,如果您使用線程和
sys.exc_info
您甚至可能會得到錯誤的回溯(尤其是如果您對控制流使用異常處理,我個人傾向于避免這種情況。)
Python 3,異常連結
在Python 3中,您可以連結異常,以保留回溯:
raise RuntimeError('specific message') from error
意識到:
- 這确實允許更改引發的錯誤類型,并且
- 這與Python 2 不相容。
不推薦使用的方法:
這些可以輕松隐藏甚至進入生産代碼。 您想提出一個例外,而這樣做會引發一個例外, 但不是原計劃!
在Python 2中有效,但在Python 3中無效 :
raise ValueError, 'message' # Don't do this, it's deprecated!
僅在更舊的Python版本 (2.4及更低版本 )中有效,您仍然可以看到有人在引發字元串:
raise 'message' # really really wrong. don't do this.
在所有現代版本中,這實際上會引發TypeError,因為您沒有引發BaseException類型。 如果您沒有檢查正确的例外情況,并且沒有知道該問題的審閱者,那麼它可能會投入生産。
用法示例
我提出異常以警告使用者如果我的API使用不正确:
def api_func(foo):
'''foo should be either 'baz' or 'bar'. returns something very useful.'''
if foo not in _ALLOWED_ARGS:
raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
适當時建立自己的錯誤類型
“我想故意犯一個錯誤,以便将其排除在外”
您可以建立自己的錯誤類型,如果要訓示應用程式存在某些特定的錯誤,隻需将異常層次結構中的适當點子類化:
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
和用法:
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
#3樓
對于常見的情況,您需要針對某些意外情況抛出異常,并且您從不打算抓住它,而隻是快速失敗以使您能夠從那裡進行調試(如果發生的話)—最合乎邏輯的是
AssertionError
:
if 0 < distance <= RADIUS:
#Do something.
elif RADIUS < distance:
#Do something.
else:
raise AssertionError("Unexpected value of 'distance'!", distance)
#4樓
在Python3中,有四種用于引發異常的文法:
1. raise exception
2. raise exception (args)
3. raise
4. raise exception (args) from original_exception
1.引發異常vs. 2.引發異常(參數)
如果使用
raise exception (args)
引發異常,則在列印異常對象時将列印
args
如下例所示。
#raise exception (args)
try:
raise ValueError("I have raised an Exception")
except ValueError as exp:
print ("Error", exp) # Output -> Error I have raised an Exception
#raise execption
try:
raise ValueError
except ValueError as exp:
print ("Error", exp) # Output -> Error
3.提高
沒有任何參數的
raise
語句将重新引發最後一個異常。 如果您需要在捕獲異常之後執行一些操作然後重新引發它,這将很有用。 但是,如果以前沒有異常,則
raise
語句引發
TypeError
Exception。
def somefunction():
print("some cleaning")
a=10
b=0
result=None
try:
result=a/b
print(result)
except Exception: #Output ->
somefunction() #some cleaning
raise #Traceback (most recent call last):
#File "python", line 8, in <module>
#ZeroDivisionError: division by zero
4.從original_exception引發異常(參數)
此語句用于建立異常連結,其中響應另一個異常而引發的異常可以包含原始異常的詳細資訊-如下例所示。
class MyCustomException(Exception):
pass
a=10
b=0
reuslt=None
try:
try:
result=a/b
except ZeroDivisionError as exp:
print("ZeroDivisionError -- ",exp)
raise MyCustomException("Zero Division ") from exp
except MyCustomException as exp:
print("MyException",exp)
print(exp.__cause__)
輸出:
ZeroDivisionError -- division by zero
MyException Zero Division
division by zero
#5樓
首先閱讀現有的答案,這隻是一個附錄。
請注意,可以帶或不帶參數引發異常。
例:
raise SystemExit
退出程式,但是您可能想知道發生了什麼。是以可以使用它。
raise SystemExit("program exited")
這将在關閉程式之前将“程式退出”列印到stderr。
#6樓
隻是要注意:有時候您确實想處理通用異常。 如果要處理大量檔案并記錄錯誤,則可能要捕獲檔案發生的任何錯誤,将其記錄下來,然後繼續處理其餘檔案。 在這種情況下,
try:
foo()
except Exception as e:
print(str(e)) # Print out handled error
阻止這樣做的好方法。 您仍将要
raise
特定的異常,以便您了解異常的含義。
#7樓
抛出異常的另一種方法是
assert
。 您可以使用assert來驗證是否滿足條件,否則将引發
AssertionError
。 有關更多詳細資訊,請在此處檢視 。
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))