1. Declare exception syntax rules
-
Try finally statement
try: Detection range except Exception[as reason]: An exception occurred( Exception)Post processing code finally: Code that will be executed anyway
A try statement can be matched with multiple except statements, because there may be multiple types of exceptions in the try statement block. Multiple except statements can be used to capture and handle the exceptions we are interested in respectively.
except (OSError, TypeError, ValueError) as reason: print('Error \n The reason for the error is:' + str(reason))
-
raise statement
Used to declare an exception
>>> raise ZeroDivisionError('Exception with divisor zero') Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise ZeroDivisionError('Exception with divisor zero') ZeroDivisionError: Exception with divisor zero
Example: try a new function int_input(), when the user inputs an integer, it returns normally. Otherwise, an error will be prompted and re input is required
def int_input(prompt=''): while True: try: int(input(prompt)) break except ValueError: print('Error, the number you entered is not an integer!') int_input("Please enter an integer:")
2. Use of else statement and with statement
-
else statement
- Usage 1:
if a>b: print(a) else: print(b)
- Usage 2:
#******************************************# # Judge the maximum common divisor of a given number. If it is a prime number, print it # #******************************************# def showMaxFactor(num): count = num//2 while count > 1: if num % count == 0: print('%d The largest divisor is%d' %(num,count)) break count -= 1 else: # Only after the loop is completed can it be executed. If break is used for execution in the loop, else will not be executed print('%d It's prime!' %num) num = int(input('Please enter a number:')) showMaxFactor(num)
- Usage III
try: print(int('abc')) except ValueError as reason: print('Something went wrong:' + reason) else: # If there is no error print('No exceptions!')
-
with statement
with context_expression [as target(s)]: with-body
#**********************************# # Exception handling cooperation with sentence # # It can avoid the situation that the opened file is not closed # #**********************************# try: with open('data.txt', 'w') as f: for each_line in f: print(each_line) except OSError as reason: print('Something went wrong:' + str(reason))
3.Python standard exception summary
Exception name | explain |
---|---|
AssertionError | Assert statement failure: when the condition behind the assert keyword is false, the program will throw this exception, which is generally used to put a checkpoint in the code >>> my_list = ['hello world'] >>>Assert len (my_list) > 0 # at this time, the program has no response >>> my_list.pop() >>>Assert len (my_list) > 0 # at this time, an exception AssertionError is thrown |
AttributeError | Attempt to access an unknown object property: an exception thrown when the object property you are trying to access does not exist >>> my_list.fishc Throw an exception: AttributeError: 'list' object has no attribute 'fishc' |
EOFError | This error basically means that it found an unexpected end of the file. (Ctrl+d on UNIX and Ctrl+Z+Enter on Windows) |
FloatingPointError | Floating point calculation error |
GeneratorExit | Gengeator. When the close () method is called |
ImportError | When the import module fails |
IndexError | Index is out of range for the sequence |
KeyError | Find a keyword that does not exist in the dictionary |
KeyboardError | User input interrupt key (Ctrl+c) |
MemoryError | Memory overflow (memory can be released by deleting objects) |
NameError | An attempt was made to access a variable that does not exist |
NotImplementedError | Methods not yet implemented |
OSError | An exception generated by the operating system (for example, opening a file that does not exist) |
OverflowError | Numeric operation exceeds maximum limit |
ReferenceError | A weak reference attempts to access an object that has been garbage collected |
RuntimeError | General runtime error |
StopIteration | The iterator has no more values |
SyntaxError | Python syntax error |
IndentationError | Indent error |
TabError | Mixed use of Tab and space |
SystemError | Python compiler system error |
SystenExit | The Python compiler process was shut down |
TypeError | Invalid operation between different types |
UnboundLocalError | Access an uninitialized local variable (subclass of NameError) |
UnicodeError | Unicode related error (subclass of ValueError) |
UnicodeEncodeError | Error in Unicode encoding (subclass of Unicode error) |
UnicodeDecodeError | Error in Unicode decoding (subclass of Unicode error) |
UnicodeTranslateError | Error during Unicode conversion (subclass of Unicode error) |
ValueError | Invalid parameter passed in |
ZeroDivisionError | Divide by zero |