@(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]
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.