Python is an object-oriented language, so the exception that the program throws is also the class.
Common exception classes
1.NameError: Attempt to access a variable without a declaration
2.ZeroDivisionError: Divisor is 0
3.SyntaxError: Syntax error
4.IndexError: Index exceeded sequence range
5.KeyError: Request a dictionary keyword that does not exist
6.IOError: Input and output error (such as the file you want to read does not exist)
7.AttributeError: Attempting to access an unknown object property
8.TypeError: Incorrect parameter type passed to function, such as passing character type to int function
Custom exception Classes
Although the built-in exception classes already include most of the cases, if you need to create your own exception classes, you can use the following method:
Copy Code code as follows:
Class Customexception (Exception): # Exception is the base class for all exceptions
# code to handle exceptions
Catch exception
Copy Code code as follows:
Try
# code to catch the exception, only the code before the exception is finally executed
Except (Exception1,exception2,...) as argument:
# Capture the exception in (Exception1,exception2,...) to execute this code
# argument is an instance of an exception class that contains specific information about the exception
Except
# Catch Exceptions (Exception1,exception2,...) execute this code and use the Exc_info () function of the SYS module to get exception information
Else
# Execute this code if the exception is not caught
Finally
# executes this code whether or not an exception is caught
The above statements are not all necessary, such as try...except ..., try...finally ... Or Try...except...else ... statements are feasible. We can also use try...except...else ... Instead of if...else ....
Throw an exception
If we want to actively throw an exception in a program that we write, there are two ways to do this:
Raise Exception (reason)
Exception must be the name of an exception class. Optional reason information that is used to pass exceptions.
Assert Expression[,reason]
Assert is the keyword of the assertion. When an expression is expression true, nothing is done, or a Assertionerror exception is thrown. Reason provides information about the exception.
Context Manager
Because object file supports context management protocols, you can open the file in the following ways:
Copy Code code as follows:
with open (' filename ') as FP:
# Regardless of whether this code has an exception, the file object FP can be properly closed
Example
Copy Code code as follows:
Import Sys
def div (num, den):
Print (' _________________ (', num, ', ', den, ') \ n ')
Try
Ans = Num/den
Assert den!= num, ' Equal ' # asserts that the numerator is not equal in denominator
Den = ' Changed ' # If no exception occurs before this statement is executed, change the value of den
If num% 2: # If the molecule is odd, throw an exception
Raise ValueError (' Odd ')
Except Zerodivisionerror as E:
Print (' except ... as ... \n\t ', e)
Except
Print (' except\n\t ', Sys.exc_info ())
Else
Print (' else\n\t ', ans)
Finally
Print (' finally\n\t ', den)
Div (1,0) # divisor is zero, Zerodivisionerror exception class
Div (1,1) # numerator equals denominator, assertion is false, throw exception
Div (2,1) # no exceptions
Div (3,1) # molecule is odd, throw an exception by raise
Div (3, ' X ') # Other exceptions that do not belong to Zerodivisionerror
Run Result:
Copy Code code as follows:
_________________ (1, 0)
Except ... as .....
Division by zero
Finally
0
_________________ (1, 1)
Except
(<class ' Assertionerror ', Assertionerror (' Equal ',), <traceback object at 0x00000000029b42c8>)
Finally
1
_________________ (2, 1)
Else
2.0
Finally
Changed
_________________ (3, 1)
Except
(<class ' ValueError ', ValueError (' Odd ',), <traceback object at 0x00000000029b42c8>)
Finally
Changed
_________________ (3, X)
Except
(<class ' TypeError ', TypeError ("Unsupported operand type (s) for/: ' int ' and ' str '",), <traceback object at 0x00 000000029b42c8>)
Finally
X