Exception handling in Python study notes

  • 2020-04-02 14:31:15
  • OfStack

Python is an object-oriented language, so exceptions thrown by programs are also classes.

Common exception classes

1.NameError: try to access an undeclared variable
2.ZeroDivisionError: divisor is 0
3.SyntaxError: grammar error
4.IndexError: index beyond sequence scope
5.KeyError: request for a non-existent dictionary keyword
6.IOError: input/output error (e.g. the file you want to read does not exist)
7.AttributeError: attempt to access unknown object attributes
TypeError: the parameter type passed to the function is not correct, such as the character type passed to the int function

Custom exception classes

Although most cases are covered by the built-in exception classes, if you need to create your own exception classes, you can do the following:


class CustomException(Exception): # Exception Is the base class for all exceptions
    # Code to handle exceptions

Catch exceptions


try: 
   # The code that needs to catch the exception is the only code that is ultimately executed before the exception occurs
except (Exception1,Exception2,...) as argument: 
   # Capture the (Exception1,Exception2,...) Exception to execute this code
   # argument Is an instance of an exception class that contains specific information about the exception
except:
   # Capture the (Exception1,Exception2,...) Exception execution of this section of code, with sys The module exc_info() The function gets the exception information
else: 
   # Execute this code if no exception is caught
finally: 
   # Execute this code whether or not an exception is caught

Not all of the above statements are required, such as try... Except... , try... Finally... Or try... Except... The else... The statements are all valid. We can also use try... Except... The else... Instead of the if... The else... .

An exception is thrown

If we want to throw an exception actively in our program, we can do it in the following two ways:

Raise the Exception (reason)

Exception must be the name of an Exception class. Optional reason is used to pass the information of the exception.

Assert expression [, tiny]

Assert is the keyword for assertions. Do nothing when the expression is true, otherwise an AssertionError exception is thrown. Reason provides information about exceptions.

Context manager

Since object File supports the context management protocol, you can open the File by:


with open('filename') as fp:
   # File object whether or not this code has an exception fp All can be closed correctly

Example


import sys def div(num, den):
 print('_________________   (',num,',',den,')n')
 try:
  ans = num/den
  assert den != num, 'Equal' # Assertion: the numerator and denominator are not equal
  den = 'Changed'            # If there is no exception before executing this statement, change den The value of the
  if num % 2:                # If the numerator is odd, an exception is thrown
   raise ValueError('Odd')
 except ZeroDivisionError as e:
  print('except ... as ...nt', e)
 except:
  print('exceptnt', sys.exc_info())
 else:
  print('elsent', ans)
 finally:
  print('finallynt', den) div(1,0) # The divisor is zero ZeroDivisionError Exception class
div(1,1) # The numerator is equal to the denominator, the assertion is false, and an exception is thrown
div(2,1) # There is no abnormal
div(3,1) # The numerator is odd. It goes through raise An exception is thrown
div(3,'x') # Do not belong to ZeroDivisionError Other exceptions

Operation results:

_________________   ( 1 , 0 ) except ... as ...
  division by zero
finally
  0
_________________   ( 1 , 1 ) except
  (<class 'AssertionError'>, AssertionError('Equal',), <traceback object at 0x00000000029B42C8>)
finally
  1
_________________   ( 2 , 1 ) else
  2.0
finally
  Changed
_________________   ( 3 , 1 ) except
  (<class 'ValueError'>, ValueError('Odd',), <traceback object at 0x00000000029B42C8>)
finally
  Changed
_________________   ( 3 , x ) except
  (<class 'TypeError'>, TypeError("unsupported operand type(s) for /: 'int' and 'str'",), <traceback object at 0x00000000029B42C8>)
finally
  x


Related articles: