Python exception handling


This article lists common exception handling in Python in more detail for your reference. The details are as follows:

1. Throwing exceptions and custom exceptions

Python uses exception objects to represent abnormal situations. When an error is encountered, an exception will be thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message).

①.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("抛出一个异常")

# Exception: 抛出一个异常
ThorwErr()

The raise keyword is followed by a general exception type (Exception). Generally speaking, the more detailed the exception thrown, the better. Python is in the exceptions module There are many built-in exception types. You can use the dir function to view the exception types in exceptions, as follows:

import exceptions

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

Passing exceptions

If you catch the exception, but want to re-raise it (pass the exception), you can use the raise statement without parameters:

# -- 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

②.Auto Define exception types

You can also customize your own special type of exception in Python. You only need to inherit from the Exception class (directly or indirectly):

class SomeCustomException(Exception):
  pass

2. Catching exceptions

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

# -- coding: utf-8 --

try:
  print 2/0
except ZeroDivisionError:
  print '除数不能为0'

①.Catch multiple exceptions

In an except statement, only the exception type declared subsequently is caught, if other exceptions may be thrown Type of exception requires adding an except statement, or you can specify a more general exception type such as Exception, as follows:

# -- coding: utf-8 --
try:
  print 2/'0'
except ZeroDivisionError:
  print '除数不能为0'
except Exception:
  print '其他类型异常'

In order 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 '发生了一个异常'

②. Get Exception information

Each exception will have some exception information. Under normal circumstances, we should record these 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. finally clause

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

# -- coding: utf-8 --
try:
  print 2/'0'
except (ZeroDivisionError,Exception):
  print '发生了一个异常'
finally:
  print '不管是否发生异常都执行'