10th Chapter Exception
First, abnormal
1 Detecting and handling exceptions
(1) Try-except statement
Try
Try_suite #监控这里的异常
Except exception[, reason]:
Except_suite #异常处理代码
(2) "Try statement with multiple except" and "except statement to handle multiple exceptions"
(3) Catch all exceptions
Try
:
Except Exception, E:
# error occurred, log ' e ', etc.
(4) Exception parameters
(5) ELSE clause and finally clause
(6) try-except-else-finally: Kitchen Yiguoduan
Try
Try_suite
Except Exception1:
Suite_for_exception1
Except (Exception2, Exception3, Exception4):
Suite_for_exceptions_2_3_and_4
Except Exception5, ARGUMENT5:
Suite_for_exception5_plus_argument
Except (Exception6, Exception7), Argument67:
Suite_for_exceptions6_and_7_plus_argument
Except
Suite_for_all_other_exceptions
Else
No_exceptions_detected_suite
Finally
Always_execute_suite
2 Context Management
With statement:
With context_expr [as Var]:
With_suite
Example:
With open ('/etc/passwd ', ' R ') as F:
For Eachline in F:
# ... do stuff with eachline or f ...
Note: regardless of the beginning of this section of code, the middle, or the end of an exception occurs, the cleanup code will be executed, and the file will still be automatically closed.
3 Triggering exceptions
raise [Someexception [, Args [, Traceback]]
4 Standard Exceptions
Second, assert
Assert expression[, arguments]
Python core Programming Read Pen 8: exception