Python exception handling summary

  • 2020-04-02 13:54:44
  • OfStack

This article lists the common exception handling of Python in detail, for your reference, as follows:

1. Throws exceptions and custom exceptions

Python USES an exception object to represent an exception case, which is thrown when an error is encountered. If the exception object is not handled or caught, the program terminates execution with what is called a Traceback (an error message).

1. Raise statement

The raise keyword in Python is used to raise an exception, which is basically the same as the throw keyword in C# and Java, as shown below:


# -- coding: utf-8 --

def ThorwErr():
  raise Exception(" Throw an exception ")

# Exception:  Throw an exception 
ThorwErr()

In general, the more specific the Exception is, the better. Python has built a lot of Exception types into the exceptions module. The dir function is used to check the Exception types in exceptions, as follows:


import exceptions

# ['ArithmeticError', 'AssertionError'.....]
print dir(exceptions)

Abnormal transfer

An exception is caught, but if you want to raise it again (pass the exception), you can simply use the raise statement with no arguments:


# -- coding: utf-8 --
class MuffledCalculator:
  muffled = False
  def calc(self,expr):
    try:
      return eval(expr)
    except ZeroDivisionError:
      if self.muffled:
        print 'Division by zero is illegal'
      else:
        raise

Ii. Custom exception types

Python can also customize its own special type of Exception by inheriting (directly or indirectly) from the Exception class:


class SomeCustomException(Exception):
  pass

2. Catch exceptions

Similar to the try/catch in C#, the try/except keyword is used in Python to catch exceptions, as follows:


# -- coding: utf-8 --

try:
  print 2/0
except ZeroDivisionError:
  print ' The divisor cannot be zero 0'

. Catch a number of exceptions

An except statement captures only the types of exceptions that are declared later, except if other types of exceptions are likely to be thrown, or you can specify a more general type of Exception such as: Exception, as follows:


# -- coding: utf-8 --
try:
  print 2/'0'
except ZeroDivisionError:
  print ' The divisor cannot be zero 0'
except Exception:
  print ' Other types of exceptions '

To catch multiple exceptions, in addition to declaring multiple except statements, you can also list multiple exceptions as tuples after an except statement:


# -- coding: utf-8 --
try:
  print 2/'0'
except (ZeroDivisionError,Exception):
  print ' An exception has occurred '

. Get the exception information

Each exception will have some exception information, in general, we should record the exception information:


# -- coding: utf-8 --
try:
  print 2/'0'
except (ZeroDivisionError,Exception) as e:
  # unsupported operand type(s) for /: 'int' and 'str'
  print e

3. The finally clause

The finally clause is used in conjunction with the try clause, but unlike the except statement, the code in the finally clause is executed regardless of whether an exception occurs inside the try clause. In all general cases, finally itself is often used to close files or in sockets.


# -- coding: utf-8 --
try:
  print 2/'0'
except (ZeroDivisionError,Exception):
  print ' An exception has occurred '
finally:
  print ' Execute whether an exception occurs or not '

Related articles: