Python exception handling

Time:2021-3-3

Distinguish exception from syntax error

When writing Python programs, errors are often reported. There are usually two kinds of errors:

  1. Syntax error:Some grammatical errors are exceptions
  2. Exception

syntax error

Syntax error, also known as parsing error, is one of the most common errors

In [1]: while True print('Hello!')
  File "<ipython-input-1-5c66e4fd0ae9>", line 1
    while True print('Hello!')
                   ^
SyntaxError: invalid syntax

Syntax error is thrown when the code does not conform to Python syntax.

abnormal

Python uses exception objects to represent exceptions. When an error is encountered, an exception is thrown. If the exception is not handled or caught, the program uses thetracebackTerminate the execution of the program. If it is in a multithreaded program, it will terminate the execution of the current thread.

In [2]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-05c9758a9c21> in <module>()
----> 1 1/0

ZeroDivisionError: division by zero

When divided by 0, a zerodivisionerror exception (an instance of the zerodivisionerror class) is thrown.

<!–more–>

Exception hierarchy

The class hierarchy of built-in exceptions in Python 3.5.2 is as follows: refer to the standard library

Baseexception # the base class of all exceptions
 +--Systemexit # program exit / termination
 +--Keyboardinterrupt # generated by keyboard interrupt (usually Ctrl + C)
 +--Generatorexit # is raised by the generator. Close() method
 +--Exception # the base class of all non exit exceptions
      +--Stopiteration # stop iteration error
      +--Stopasynciteration # stop asynchronous iteration error
      +--The base class of arithmetical error # arithmetic anomaly
      |+ -- floatingpointerror # floating point operation exception
      |+ -- overflow error ා exception caused by overflow
      |+ -- zerodivisionerror # exception caused by division of 0 or mode fetching operation
      +--Assertionerror # is raised by the assert statement
      +--Attributeerror # raised when the attribute name is invalid
      +--Buffererror # caused by a buffer error
      +--Eomirror # is raised when it reaches the end of the file
      +--Importerror # import statement failed
      +--Lookuperror # index and key error
      |+ -- indexerror # out of range of sequence index
      |The + -- keyerror key does not exist
      +--Memoryerror # out of memory
      +--NameError # unable to find local or global name
      |+ -- unboundlocalerror # unbound local variable
      +--Oserror? Operating system error
      |+ -- blocking ioerror # IO blocking
      |+ -- childprocesserror child process
      |+ -- connectionerror # connection error
      || + -- broken pipeerror
      || + -- connectionabortederror # connection aborted
      || + -- connectionrefusederror # connection rejected
      || + -- connectionreseterror # connection reset
      |+ -- fileexistserror # the file already exists
      |+ -- filenotfounderror # file does not exist
      |+ -- interruptederror # interrupt error
      |+ -- isadirectoryerror # directory error
      |+ -- notadirectoryerror # non directory error
      |+ -- permissionerror # permission error
      |+ -- processlookuperror # process lookup error
      |+ -- timeouterror # timeout error
      +--Referenceerror # the reference is still used after the referenced object is destroyed
      +--Runtimeerror # runtime error
      |+ -- not implemented error # features not implemented
      |+ -- recursionerror # recursive error
      +--Syntax error # syntax error
      |+ -- indentation error
      |+ -- taberror # use inconsistent tabs
      +--Non fatal system error in systemerror # interpreter
      +--Typeerror # passed the wrong type to the operation
      +--Valueerror # invalid type
      |+ -- Unicode error # Unicode error
      |+ -- Unicode decodeerror # Unicode decoding error
      |+ -- Unicode encodeerror # Unicode encoding error
      |+ -- Unicode translateerror # Unicode conversion error
      +--The base class of warning
           +--Warning about discarded features
           +--Warning about feature being discarded
           +--Runtimewarning # warning of suspicious runtime behavior
           +--Syntax warning
           +--Userwarning # user code generation warning
           +--Futurewarning # warning about future semantic changes in construction
           +--Warning for importwarning # import statement
           +--Unicode warning # Unicode warning
           +--Byteswarning # bytes warning
           +--Resourcewarning? Resource warning
  • The base class of all exceptions is baseexception
  • Except systemexit, keyboardinterrupt and generatorexit, they all inherit from exception

Catch exception

The try / except statement can be used to catch exceptions. The try / except statement is used to detect the errors in the try statement block, so that the except statement can catch the exception information and handle it.

try/except

Basic grammar

try:
    < sentence >
except <name>:
    < sentence >          #如果在try部分引发了名为'name'的异常,则执行这段代码

Examples

In [3]: try:
   ...:     x = int(input("Please enter a number: "))
   ...: except ValueError:
   ...:     print("No valid number.")
   ...:     
Please enter a number: asd
No valid number.

Multiple exceptions

In [4]: import sys

In [5]: try:
   ...:     f = open(' file.txt The filenotfounderror exception is thrown when the file does not exist
   ...:     s = f.readline()
   ...:     i = int(s.strip())
   ...: except oserror: # filenotfounderror: the upper exception of the exception
   ...:     print('OS error.')
   ...: except ValueError:
   ...:     print('Could not convert data to integer.')
   ...: except Exception:
   ...:     print('Exception.')
   ...: except: # all exceptions will be caught when no specific exception type is added, which should not be used or used with caution
   ...:     print('Unexpected error:', sys.exc_info()[0])
   ...:     
OS error.

The execution sequence of each exception is as follows:

  • Exception sequentially captures the exception thrown in try
  • The more specific an exception is, the more advanced it should be, and the more general an exception is, the more backward it should be

Optional else statement

grammar

try:
    < sentence >
except <name>:
    < sentence >          #如果在try部分引发了名为'name'的异常,则执行这段代码
else:
    < sentence >          #如果没有异常发生,则执行这段代码

If the try part does not throw an exception, but the statement must be executed, it is placed in the else statement.

code

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    Else: # print out every line in the file when no exception is thrown (that is, the file is opened correctly)
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

Finally statement

Finally statement is used to define the statement that must be executed in any case.

In [1]: try:
   ...:     raise KeyboardInterrupt
   ...: finally:
   ...:     print('Goodbye')
   ...:     
Goodbye
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-8-132d568ca0fb> in <module>()
      1 try:
----> 2     raise KeyboardInterrupt
      3 finally:
      4     print('Goodbye')
      5 

KeyboardInterrupt:

Finally execution order with return statement

def p(x):
    print(x)
    return x

def t():
    try:
        return p(2)
        print('haha')
    finally:
        return p(3)

x = t()

#The output results are as follows
2
3
#The return value x is 3

It can be seen that as long as there is a finally statement in the try block, even if the function returns in advance, the finally statement will be executed before exiting the try block, so the return value will be replaced by the return statement in finally.

Examples of comprehensive use

In [1]: def divide(x, y):
   ...:     try:
   ...:         result = x / y
   ...:     except ZeroDivisionError:
   ...:         print('division by zero!')
   ...:     else:
   ...:         print('result is ', result)
   ...:     finally:
   ...:         print('executing finally clause.')
   ...:         

In [2]: divide(2, 0)
division by zero!
executing finally clause.

In [3]: divide(2, 1)
result is  2.0
executing finally clause.

In [4]: divide('2', '1')
executing finally clause.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-34bb38fa74fd> in <module>()
----> 1 divide('2', '1')

<ipython-input-1-4273ffa41b76> in divide(x, y)
      1 def divide(x, y):
      2     try:
----> 3         result = x / y
      4     except ZeroDivisionError:
      5         print('division by zero!')

TypeError: unsupported operand type(s) for /: 'str' and 'str'

Conclusion

  • In any case, the finally statement is executed.
  • Even if there is a return statement in the try part, the finally statement will be executed before exiting the try block, and the return value is finally
  • If an exception is not handled, the unhandled exception will be thrown after the finally statement is executed
  • In practice, finally is usually used to release additional resources, such as files or network connections

Actively throw an exception

Raise statement

In [1]: raise NameError('Hello')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-64f372e60821> in <module>()
----> 1 raise NameError('Hello')

NameError: Hello

User defined exception

When users define exception classes, they should inherit from exception classes directly or indirectly.

class CustomException(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message

try:
    raise CustomException(500, 'error')
except CustomException as e:
    print('{},{}'.format(e.code, e.message))

#Output result: 500, error

Exception passing

When an exception is thrown inside a function, if the exception is not caught, it is propagated to where the function is called.

In [1]: def a():
   ...:         raise Exception('Hello')
   ...: 

In [2]: def b():
   ...:         print('enter b')
   ...: a() # the exception thrown in function a will be passed to the calling out of the parent function
   ...: Print ('exit B ') # a throws an exception and passes it to B to abort the execution of B
   ...:     

In [3]: b()
enter b
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-3-9c619ddbd09b> in <module>()
----> 1 b()

<ipython-input-2-f99a565bd6f8> in b()
      1 def b():
      2         print('enter b')
----> 3         a()
      4         print('exit b')
      5 

<ipython-input-1-6e68e60e93b5> in a()
      1 def a():
----> 2         raise Exception('Hello')

Exception: Hello

Remember to praise me!

We have carefully arranged video courses and e-books from entry-level, advanced and practical in all directions of computer. We can always find the learning materials you need according to the reasonable classification of the catalogue. What are you waiting for? Pay attention to download it!!!

Python exception handling

If you don’t forget, there will be an echo. Please give me a compliment. Thank you very much.

I am a bright brother in the workplace, YY Senior Software Engineer, with four years of working experience. I refuse to be a leading slash programmer.

Listen to me, more progress, a shuttle of procedural life

If you are lucky enough to help you, please give me a “like” to pay attention to it. If you can comment on it and give me encouragement, I will be very grateful.

List of articles of workplace bright brother:More articles

Python exception handling

All my articles and answers have cooperation with the copyright protection platform. The copyright belongs to brother Liang in the workplace. Without authorization, reprint must be investigated!