Python exception handling,
Exception Handling Format:
Try:
Execute Statement 1
Raise custom exception type ()
T custom exception type:
Execute Statement 2
Handle T (exception Type 1, exception type 2 ,......) :# Separate multiple exception types with commas
Execute Statement 3
Failed t Exception:# Omnipotent match. No error type is returned!
Execute Statement 4
Else:
Execute Statement 5
Finally:
Execute Statement 6
Brief description:
1. The raise statement can customize the error message, as shown above.
2. After raise, the statement will not be executed. Because an exception has been thrown, the control flow will jump to the exception capture module.
3. the except statement can contain multiple exceptions after a except statement, or capture multiple exceptions with multiple statements for different processing. If you do not know the specific Exception type, you can use Exception for universal matching.
4. if exceptions caught by the explain T statement do not occur, the statement blocks in explain T will not be executed. Instead, execute the statements in else.
5. in the preceding statement, try/try t/else/finally appears in the order of try-> try t X-> try t-> else-> finally, that is to say, all the except T must be before else and finally, else (if any) must be before finally, and except t x must be before except T. Otherwise, a syntax error occurs.
6. else and finally are both optional.
7. In the preceding complete statement, the existence of the else statement must be subject to the limit t x or limit t statement. If you use the else statement in a try block without the limit t statement, a syntax error occurs.
Code example:
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
Class MyError (Exception): # customize an Exception class MyError, inheriting the parent class Exception (Exception omnipotent class)
Def _ init _ (self, message ):
Self. message = message
Self. code = 100
Def _ str _ (self ):
Return self. message
Try:
Def get_num ():
Num = int (input ("input an even number >>>:"). strip ())
If num % 2! = 0:
Raise MyError ("error message: you do not enter an even number") # The raise statement automatically triggers an exception.
Get_num ()
Failed t MyError as e: # matching custom exception
Print (e) # error message
Print ("error code: % d" % e. code) # error code prompt
Failed t ValueError: # matching built-in exception
Print ("You entered not an integer ")
Failed t Exception:
Print ("Unknown error! ")
Else:
Print (">>>: the input is correct ")
Finally:
Print ("------ whether the input is correct or not, execute ------")