Python basis (VII): Exception Handling

Exception handling is a guarantee mechanism to ensure that the program runs under control, the implementation of response measures when an exception occurs the program to ensure that the program does not directly hang up, and let the exception information tracked, so a reasonable exception handling mechanism also guarantee program one of the key factors robustness.

 

In Python, exception handling process structure as follows,

the try : 
    code block. 1 
the except Exception AS E: 
    block 2 
    The raise E
 the else : 
    block. 3 
the finally : 
    block 4

 

The following detailed description of the use of each keyword,

1、try

If the program has some operations may appear abnormal, then put the code on the back of a try statement, such as some user input, file reading and other operations.

2、except

When abnormality occurs inside the code try, the except where the code executes, mainly for capturing and processing this exception, the except there may be a plurality, but exceptions are not the same each time the captured, somewhat similar to the condition judgment elif, except one time and can catch multiple exceptions, anomalies in the manner of a tuple record, but this is not recommended, because doing so may not be able to distinguish which in the end there was an exception.

3、else

If you try inside the code without any anomaly is present else in the code will be executed, and except it is two different branches, so except else and can not run simultaneously.

4、finally

Whether there is no abnormality in front, finally the final statement will be executed.

5、raise

The captured explicit exception out, if a custom exception may not be required raise.

 

Base class for all exception classes: BaseException

Guess you like

Origin www.cnblogs.com/suanmiaoup/p/12174858.html