Python異常

重要的是要有一種處理錯誤的方法。

Python為我們提供了異常處理。

如果將代碼行包裝到try:堵塞:

try:
    # some lines of code

如果發生錯誤,Python會提醒您,您可以使用except塊:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>

要捕獲所有異常,您可以使用except沒有任何錯誤類型:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except:
    # catch all other exceptions

else如果未發現異常,則運行塊:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully

一種finally塊允許您在任何情況下都執行某些操作,無論是否發生錯誤

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully
finally:
    # do something in any case

將要發生的特定錯誤取決於您正在執行的操作。

例如,如果您正在讀取文件,則可能會得到一個EOFError。如果將數字除以零,則會得到一個ZeroDivisionError。如果您遇到類型轉換問題,則可能會收到TypeError

試試下面的代碼:

result = 2 / 0
print(result)

該程序將以錯誤終止

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = 2 / 0
ZeroDivisionError: division by zero

and the lines of code after the error will not be executed.

Adding that operation in a try: block lets us recover gracefully and move on with the program:

try:
    result = 2 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
finally:
    result = 1

print(result) # 1

You can raise exceptions in your own code, too, using the raise statement:

raise Exception('An error occurred!')

This raises a general exception, and you can intercept it using:

try:
    raise Exception('An error occurred!')
except Exception as error:
    print(error)

You can also define your own exception class, extending from Exception:

class DogNotFoundException(Exception):
    pass

pass here means “nothing” and we must use it when we define a class without methods, or a function without code, too.

try:
    raise DogNotFoundException()
except DogNotFoundException:
    print('Dog not found!')

More python tutorials: