This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging
Preface – What are Exceptions?
An exception is an event that occurs during the execution of the program and affects the normal execution of the program.
Normally, an exception occurs when Python cannot handle the program properly.
An exception is a Python object that represents an error.
When an exception occurs in a Python script, we need to catch it, or the program will terminate execution.
Part ONE: Exceptions
Note: When an exception occurs, the rest of the code is not executed.
Exceptions themselves are classes
Tips:
All exceptions in Python are inherited from BaseException
Directly divided into four categories:
- SystemExit: Python exit exception
- KeyboardInterrupt (Ctrl+C)
- GeneratorExit: The generator exits
- Exception: normal Exception (only this part of the Exception will be used)
Part two: Exception handling
1. Basic try… except…
For example:
Try: print(11) # print(a) # print(22) # except: print(' there is an exception ')Copy the code
Output:
11
There is an exception
Note: except must follow try
2. Catch specific exceptions
Except can be followed by the specific exception type to be caught
You can also use as to store the caught exception information in a later variable
Example:
Try: print(11) print(a) print(22) except NameError as t: Print (' there is an Exception here ') print(' error cause: %s'%t)Copy the code
Output:
11
There is an exception
Error: Name ‘a’ is not defined
3. Catch multiple exceptions
You can write more than one except
try:
pass
except TabError:
pass
except NameError:
pass
Copy the code
Writing method 2: use parentheses to enclose the various exception types after except
try:
pass
except (NameError,TabError):
pass
Copy the code
If unsure of the exception type:
Try: pass except ExceptionCopy the code
Explanation of Exception and its subclasses
All exceptions that occur in your code are subclasses of Exception, so add Exception at the end of except
During the process of catching an exception, the exception will be compared from the top to the bottom, and once found, there will be no further search
4. Richer structure:
Try: print(11) print(a) print(22) except Exception as result: print(' print ') else: Print (' no exception caught, execute me ') finally: print(' I execute with or without exception ')Copy the code
Notes:
- Under try, put the code that might go wrong
- When the code under except try fails, the code under except try is executed
- Finally executes regardless of whether the code below the try has an error
5. Extensions (custom exception types)
Raise Raises an exception
Format: raise Exception type
Note: Raise is an exception type written after the active raise
(1) You can write your own custom exception:
Class WuMou(Exception): pass raise WuMou(' error occurred ')Copy the code
The output is:
Traceback (most recent call last): File “C:/my/pycharm_work/ceshi.py”, line 3, in raise WuMou(‘ error occurred ‘) main.WuMou: Error occurred
This exception can be caught:
Class WuMou(Exception): pass try: raise WuMou(' error occurred ') except WuMou as h: print(h)Copy the code
The output is:
There is an error
(2) Examples:
Raise NameError(' an error occurred ')Copy the code
The output is:
Traceback (most recent call last): File “C:/my/pycharm_work/ceshi.py”, line 2, in raise NameError(‘ error ‘) : Something went wrong
6. Use with catch exceptions:
If 1 == 1: raise NameError(‘ error occurred ‘) except Exception as e: print(e)
Output: an error occurred
Except accepts an exception and can throw or return an exception else executes when there is no exception, finally executes whether or not there is an exception
Part three: Assertions
Question 1: How can you enforce a condition in your code?
Question 2: Is there a special syntax for this?
Assertions assert
Assertion statements are a convenient way to insert debug assertions into a program
The syntax rules for assert are:
The expression returns True with no error. The expression returns False with an AssertionError
Here’s a simple example:
A = input(' who are you? ') assert a == 'print(' welcome you? ')Copy the code
The first output is: who are you: Welcome to Wu
The second type of output is: Who are you? File “C:/my/pycharm_work/ceshi.py”, line 2, in assert a == ‘wu ‘,’ You are not Wu’ AssertionError: You are not Wu
An example of an upgrade:
A = input(' who are you? ') try: assert a == 'who are you?' print(' Welcome you? ') except AssertionError as f: print(f)Copy the code
The first kind of output: who are you: Welcome you Wu
The second kind of output: Who are you: China you are not Wu