Python 中的異常的引數
異常可以包含一個引數,此引數是提供有關問題更多資訊的值。引數的內容因異常而異。你可以透過在 except 子句中提供一個變數來捕獲異常的引數,如下所示 −
try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here...
如果你編寫程式碼來處理單個異常,則可以在 except 語句中讓變數跟在異常名稱之後。如果你正在捕獲多個異常,則可以在異常的元組後跟一個變數。
此變數接收異常的值,其中大部分包含異常的原因。該變數可以接收一個值或以元組形式接收多個值。此元組通常包含錯誤字串、錯誤編號和錯誤位置。
示例
以下是單個異常的示例 −
#!/usr/bin/python # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz");
輸出
產生以下結果 −
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
廣告