Python exception handling

Distinguish between Exception and Syntax Error

Errors are often reported when writing Python programs. Errors usually have the following two situations:

  1. Syntax Error: Some syntax errors are exceptions
  2. Exception

Grammatical errors###

Syntax errors are also called parsing errors and are the most common type of error encountered

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

SyntaxError will be thrown when the code does not conform to Python syntax.

abnormal###

Python uses exception objects to represent abnormal situations. After encountering an error, an exception is raised. If the exception is not handled or caught, the program will use traceback to terminate the execution of the program, if it is in a multi-threaded 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>()---->11/0

ZeroDivisionError: division by zero

When dividing by 0, a ZeroDivisionError exception (an instance of the ZeroDivisionError class) will be thrown.

Exception hierarchy##

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

BaseException  #Base class for all exceptions
 +- - SystemExit  #Program exit/termination
 +- - KeyboardInterrupt  #Interrupted by the keyboard (usually Ctrl+C)generate
 +- - GeneratorExit  #By the generator.close()Method trigger
 +- - Exception  #Base class for all non-exit exceptions
  +- - StopIteration  #Stop iteration error
  +- - StopAsyncIteration  #Stop asynchronous iteration error
  +- - ArithmeticError  #Base class for arithmetic exceptions
  |+- - FloatingPointError  #Floating point operation exception
  |+- - OverflowError  #Exception caused by overflow
  |+- - ZeroDivisionError  #Exception caused by division or modulo operation of 0
  +- - AssertionError  #Raised by the assert statement
  +- - AttributeError  #Raised when the attribute name is invalid
  +- - BufferError  #Buffer error raised
  +- - EOFError  #Raised when the end of the file is reached
  +- - ImportError  #import statement failed
  +- - LookupError  #Index and key errors
  |+- - IndexError  #Out of range of sequence index
  |+- - KeyError  #Key does not exist
  +- - MemoryError  #Not enough storage
  +- - NameError  #Cannot find local or global name
  |+- - UnboundLocalError  #Unbound local variables
  +- - OSError  #Operating system error
  |+- - BlockingIOError  #IO blocking
  |+- - ChildProcessError  #Child process
  |+- - ConnectionError  #connection error
  ||+- - BrokenPipeError  #Pipe disconnected
  ||+- - ConnectionAbortedError  #Connection aborted
  ||+- - ConnectionRefusedError  #Connection refused
  ||+- - ConnectionResetError  #Connection reset
  |+- - FileExistsError #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
  |+- - NotImplementedError  #Features not implemented
  |+- - RecursionError  #Recursion error
  +- - SyntaxError  #Grammatical errors
  |+- - IndentationError  #Indentation error
  |+- - TabError  #Use inconsistent tabs
  +- - SystemError  #Non-fatal system error in the interpreter
  +- - TypeError  #The wrong type was passed to the operation
  +- - ValueError  #Invalid type
  |+- - UnicodeError  #Unicode error
  |+- - UnicodeDecodeError  #Unicode decoding error
  |+- - UnicodeEncodeError  #Unicode encoding error
  |+- - UnicodeTranslateError  #Unicode conversion error
  +- - Warning  #Base class for warning
   +- - DeprecationWarning  #Warning about deprecated features
   +- - PendingDeprecationWarning  #Warning about features that will be obsolete
   +- - RuntimeWarning  #Warning of suspicious runtime behavior
   +- - SyntaxWarning  #Suspicious syntax warning
   +- - UserWarning  #Warning generated by user code
   +- - FutureWarning  #Warning about structural changes in semantics in the future
   +- - ImportWarning  #Warning for import statement
   +- - UnicodeWarning  #Unicode warning
   +- - BytesWarning  #Bytes warning
   +- - ResourceWarning  #Resource warning

Catch exception##

You can use try/except statements to catch exceptions. The try/except statement is used to detect errors in the try statement block, so that the except statement captures the exception information and handles it.

try/except

Basic grammar

try:<Statement>
except <name>:
 < Statement>          #If it is called in the try section'name'Exception, execute this code

Example

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 except

In [4]:import sys

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

The order of execution between each except:

Optional else statement###

grammar

try:<Statement>
except <name>:
 < Statement>          #If it is called in the try section'name'Exception, execute this code
else:<Statement>          #If no exception occurs, execute this code

If the try part does not throw an exception, but the statement that must be executed 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###

The finally statement is used to define a statement that must be executed under any circumstances.

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

KeyboardInterrupt:

The finally execution order with return statement

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

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

x =t()

# The output is:
23
# The return value x is 3

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

Comprehensive usage example

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

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

in conclusion:

Actively throw exceptions##

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 a user defines an exception class, it should directly or indirectly inherit from the Exception class.

classCustomException(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 delivery##

When an exception is raised in a function, if the exception is not caught, it will be propagated to the place where the function is called.

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

In [2]: def b():...:print('enter b')...:a()  #The exception raised in function a will be passed to the call of the parent function
 ...: print('exit b')  #After the exception is thrown in a, it is passed to b and the execution of b is suspended
   ...:     

In [3]:b()
enter b
---------------------------------------------------------------------------
Exception                                 Traceback(most recent call last)<ipython-input-3-9c619ddbd09b>in<module>()---->1b()<ipython-input-2-f99a565bd6f8>inb()1 def b():2print('enter b')---->3a()4print('exit b')5<ipython-input-1-6e68e60e93b5>ina()1 def a():---->2         raise Exception('Hello')

Exception: Hello

Recommended Posts

Python exception handling
Python common exception handling mechanism
Python exception handling
Python runtime exception management solution
Python error handling assert detailed explanation
Python&#39;s exception concept introduction and handling
Python multithreading
A practical guide to Python file handling
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
Python basics
Python descriptor
Python basics 2
Python exec
Python3 tuple
Python decorator
Python IO
Python multithreading
Python toolchain
Comprehensive summary of Python built-in exception types
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5