Exception overview
Exception refers to the error caused when the program is running. There are many reasons for the error, such as syntax error, logic error, etc. if these errors are not handled, the program will terminate
In the program, when python detects an error, the interpreter will point out that the current process cannot continue, and will give relevant prompts for the error, as shown in the following example:
The above prompt tells us that strings and integers cannot be added. TypeError is a built-in exception class in python. There are many exception classes like this in python
Exception class
Exception class | describe |
---|---|
Exception | Base class for all exceptions |
ZeroDivisionError | Divisor is 0 |
TypeError | The incoming object type is not acceptable |
NameError | Variable not declared |
IndexError | Index out of sequence range |
KeyError | A dictionary keyword that does not exist was requested |
ValueError | The parameter type passed into the function is incorrect |
AttributeError | An attempt was made to access an unknown object property |
Exception capture and handling
In order to prevent the program from terminating unexpectedly due to exceptions, the possible exceptions should be caught and handled during development,
Try except statement
Syntax format:
try: Statements with possible exceptions except Exception class name: Statement handling exception except Exception class name: Statement handling exception except ... ...
When an error occurs in a statement under try, the program will directly jump to the except statement. Let's see an example of the program
Case 1: program exception capture
try: choice='' while choice!='f': a=int(input('Please enter an integer:')) b=int(input('Please enter another integer:')) print('a/b The result of integer division is:',a/b) choice=input('Continue: (yes) y no f):') except ZeroDivisionError: print('Divisor cannot be zero!') except ValueError: print('Invalid parameter entered')
Operation results
From the above program, we can see that the program did not execute the print statement under try, because the program caught an error with divisor 0 and processed it, so the program can end normally
Get exception information using as
as statement converts the captured exception class into an exception object, and the exception information can be accessed through the exception object name
Single exception class information
Syntax format
try: Statements with possible exceptions except Exception class name as Exception object name: Statement handling exception
Multiple exception class information
Syntax format:
try: Possible exception classes except (Exception class name 1,,Exception class name 2,..) as Exception object name: Statement handling exception
Case 2: use the as statement to return the caught exception
try: choice='' while choice!='f': a=int(input('Please enter an integer:')) b=int(input('Please enter another integer:')) print('a/b The result of integer division is:',a/b) choice=input('Continue: (yes) y no f):') except (ZeroDivisionError,ValueError) as e: print(type(e),e)
Operation results
Try except else statement
It is often used to handle cases where exceptions are not caught. When exceptions are caught successfully, else statements are not executed
:
Syntax format:
try: Statements with possible exceptions except Exception class name as Exception object name: The statement that handles the exception after the exception is caught else: No abnormally executed statements were caught
Case 3: use of else statement during exception capture
try: a=int(input('Please enter an integer:')) b=int(input('Please enter another integer:')) c=a/b except BaseException as e: print('Please check whether the entered data is legal',e) else: print('The program execution result is:',c)
Operation results
Try finally statement
The finally statement block is executed regardless of whether an exception occurs in the try statement. It is often used to clean up the operations performed in the try statement, such as releasing the memory occupied by it
Syntax format:
try: Statements with possible exceptions finally: Other statements
Case 4: use of finally statement during exception capture
try: file1=open('123.txt') line=file1.readline() print(line) finally: file1.close()
Trigger exception
There are two conditions for triggering exceptions:
- An exception is automatically triggered due to an error during program execution
- Explicitly use raise or assert statements to manually trigger exceptions
raise statement
-
Trigger exception by class name
You only need to specify the exception class to create an instance object of the exception class and trigger the exception
Syntax format: raise exception class name
-
Exception triggered by instance object
You only need to specify the instance object of the exception class to trigger the exception
Syntax format: instance object of raise exception class ('specify exception information ')
assert statement
assert statement, also known as assertion statement, is mainly used to express some judgment conditions of an object in the program
Syntax format: assert expression [, parameter]
If the expression is true, no exception will be triggered. If the expression is false, an AssertError exception will be triggered. Optional parameters can be thrown as part of the exception information
Custom exception
python's built-in exception class is limited after all. It can be used to set other exceptions according to requirements
Case 5: customize a class that can only take positive numbers
class NumberError(Exception): # Inherit parent class def __init__(self,data): super().__init__(self,data) # Inherit the parent class construction method and add a parameter self.data=data def __str__(self): return self.__class__.__name__+':'+self.data+'illegal value(negative)' # __Class_ represents the class of the object under current operation, try: num=input('Please enter a positive number:') if int(num)<=0: raise NumberError(num) print('The positive number entered is:',num) except BaseException as e: print(e)
Operation results