Python錯誤處理機(jī)制

@(python程序員)[Python]


Python Cookbook

捕獲所有的異常

處理異常的時候最好還會盡可能地使用精確的異常類。

def parse_int(s):
    try:
        n = int(v)
    except Exception as e:
        print("Couldn't parse")
        print("Reason:",e)

parse_int('42')
#Couldn't parse
#Reason: name 'v' is not defined

Learning Python

Exception Basics

Suppose we write the following function:

def fetcher(obj, index):
    return obj[index]

x = 'spam'
fetcher(x, 3)
#'m'

Catching Exceptions

def catcher():
    try:
        fetcher(x, 4)
    except IndexError:
        print('got exception')
    print('continuing')

catcher()
#got exception
#continuing

Raising Exceptions

try:
    raise IndexError # Trigger exception manually
except IndexError:
    print('got exception')

Exception Coding Details

  • try/except
    Catch and recover from exceptions raised by Python, or by you.
  • try/finally
    Perform cleanup actions, whether exceptions occur or not.
  • raise
    Trigger an exception manually in your code.
  • assert
    Conditionally trigger an exception in your code.
  • with/as
    Implement context managers in Python 2.6, 3.0, and later (optional in 2.5).

The try/except/else Statement

try:
    statements # Run this main action first
except name1:
    statements # Run if name1 is raised during try block
except (name2, name3):
    statements # Run if any of these exceptions occur
except name4 as var:
    statements # Run if name4 is raised, assign instance raised to var
except:
    statements # Run for all other exceptions raised
else:
    statements # Run if no exception was raised during try block

with/as Context Managers

The basic format of the with statement looks like this

with expression [as variable]:
    with-block

Pro Python Best Practices

Exceptions in Python

The Error Type

Technically, an error message means that Python has raised an Exception. The error type indicates which Exception class was raised. All Exceptions are subclasses of the Exception class. In Python 3.5, there is a total of 47 different Exception types. You can see the full list of Exceptions with

所有的Exceptions都是Exception類的子類。在Python3.5中一共有47中Exception類型。

[x for x in dir(__builtins__) if 'Error' in x]
Figure: Hierarchy of Python Exceptions

Catching Exceptions

For sure, the following usage of try.. except is a terrible idea:

try:
    call_some_functions()
except:
    pass

This construct is known as the diaper pattern. It catches everything, but after a while you don’t want to look inside. It makes the Exception disappear, but creates a worse problem instead: the Exceptions are covered, but so are our possibilities do diagnose what is going on. A Best Practice is to use try.. except only for well-defined situations instead, and to always catch a specific Exception type.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容