Python exception handling

Posted by steven fullman on Sun, 23 Jan 2022 03:22:44 +0100

Basic concepts of Python exception handling

prit('hehe')
route
File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 3, in <module>
content
    prit('hehe')
Name: undefined name“ prit"
NameError: name 'prit' is not defined

This looks like an exception, but it's actually an exception thrown by the program
Throw exception and compile error
The exception thrown must be: Runtime

a = [1,2,3]
print(a[100])
  File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 16, in <module>
    print(a[100])
Indexer: list index out of range
IndexError: list index out of range

Open a file that does not exist

open('aaa/bbb.txt')
Traceback (most recent call last):
  File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 23, in <module>
    open('aaa/bbb.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'aaa/bbb.txt'

Exception: an error occurred while the program was running
 What exceptions will be thrown after an error according to the reason

Handling exceptions

We use try statements to catch exceptions (the code that may trigger exceptions is put into try) Use exception to handle exceptions specifically
If the exception can be caught by except, it will not affect the continued execution of the program
IndexError, e is equivalent to the name of the caught exception object is e. the exception object contains the specific information of the exception

except can specify a specific type of exception to handle
If the exception type thrown in try is not in except, the program will still terminate

try:
    a = [1,2,3]
    print(a[100])
except:
    print('Error point')
Error point

Although there are exceptions, we don't know what exceptions will occur? What kind of handling should we do for exceptions
We should know clearly that the code in try will throw those exceptions
Then targeted treatment

try:
    a = [1,2,3]
    print(a[100])
except IndexError as e:
    print('Error point',e)
Error point list index out of range

Here is name error, and out of bounds

try:
    a = [1,2,3]
    prit(a[100])
except IndexError as e:
    print('Error point',e)
Traceback (most recent call last):
  File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 58, in <module>
    prit(a[100])
NameError: name 'prit' is not defined

Modification:

try:
    a = [1,2,3]
    prit(a[100])
except IndexError as e:
    print('Error point',e)
except NameError as e:
    print('Name error',e)
Name error name 'prit' is not defined

Question: we have two exceptions. Why is there only one exception?
When we meet an exception, we won't go on,

try:
    a = [1,2,3]
    prit(a[100])
    print('hehe')
except IndexError as e:
    print('Error point',e)
except NameError as e:
    print('Name error',e)
Name error name 'prit' is not defined
 Not printed out hehe 

Question: if this code is not written by ourselves, we don't know what the exception is?

try:
    a = [1,2,3]
    prit(a[100])
    print('hehe')
except Exception as e:
    #Catch all exceptions
    print('All other exceptions',e)
All other exceptions name 'prit' is not defined

A try statement can also work with else

try:
    a = [1,2,3]
    print(a[1])
except IndexError as e:
    print('Error point',e)
except NameError as e:
    print('Name error',e)
except Exception as e:
    #Catch all exceptions
    print('All other exceptions',e)
else:
    If try If no exception is thrown in the, execute else Code in
    Such as stock try If an exception is thrown in, it will not be executed else
    print("meiyouwenti")
2
meiyouwenti

If you want to execute some code that needs to be executed regardless of whether an exception is triggered or not, you can put it in the finally statement block

try:
    a = [1,2,3]
    print(a[1])
except IndexError as e:
    print('Error point',e)
except NameError as e:
    print('Name error',e)
except Exception as e:
    print('All other exceptions',e)
else:
    print("meiyouwenti")
finally:
    Just to do some aftercare work
    You use a file. If the above exception occurs, the file will not be closed
    print('finally content')
2
meiyouwenti
finally content

Scope of variables in python
1. There are three keywords: def class lambda, which will affect the variable scope
2. Other keywords: if else while for try except
The with statement is essentially try,,, finally

Throw exception

Use the raise keyword to "throw an exception" in your code“
We implement a function to do integer division

def Divide(x, y):
    if y == 0:
        raise Exception('divide zero')
    return x / y
Divide(1, 0)
results of enforcement
Traceback (most recent call last):
  File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 156, in <module>
    Divide(1, 0)
  File "c:\Users\wyw15\Desktop\python code\testpython_5\test.py", line 154, in Divide
    raise Exception('divide zero')
Exception: divide zero

Manual throw

def Divide(x, y):
    if y == 0:
        raise Exception('The divisor is zero')
    return x / y

try:
    Divide(1,0)
except Exception as e:
    print(e)
SyntaxError: invalid syntax
 The divisor is zero

We try not to use Exception
The exception here is: ZeroDivisionError
Divide (or modulo) zero (all data types)

def Divide(x, y):
    if y == 0:
        raise ZeroDivisionError('The divisor is zero')
    return x / y

try:
    Divide(1,0)
except ZeroDivisionError as e:
    print(e)
The divisor is zero

Topics: Python Back-end