SoFunction
Updated on 2024-11-10

Python Exception Handling Summary

This article is more detailed list of common exception handling Python, for your reference, as follows:

1. Thrown exceptions and customized exceptions

Python use exception object (exception object) to represent the exception, after encountering an error, will raise an exception. If the exception object is not handled or caught, the program will use the so-called traceback (Traceback, an error message) to terminate the execution.

①.raise statement

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

# -- coding: utf-8 --

def ThorwErr():
  raise Exception("An exception was thrown.")

# Exception: throws an exception
ThorwErr()

raise keyword is followed by throw is a generic exception type (Exception), in general the more detailed the exception thrown, the better, Python in the exceptions module built-in a lot of exception types, by using the dir function to view the exception types in the exceptions, as follows:

import exceptions

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

Transfer Exception

If you catch an exception, but want to rethrow it (pass the exception), you can just use a raise statement without arguments:

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

②. Customized Exception Types

Python can also customize its own special types of exceptions, you just need to inherit (directly or indirectly) from the Exception class:

class SomeCustomException(Exception):
  pass

2. Capturing 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 'The divisor cannot be zero'

①. Catching multiple exceptions

An except statement only catches the type of exception declared after it, and if other types of exceptions may be thrown it is necessary to add another except statement, 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'
except Exception:
  print 'Other types of exceptions'

To catch multiple exceptions, in addition to declaring multiple except statements, you can simply list multiple exceptions as a tuple after an except statement:

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

②. Getting Exception Information

Every exception has some exception information, which we should normally log:

# -- 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, finally executes the code inside the finally clause regardless of whether an exception occurs inside the try clause. In general, finally is often used by itself to close a file or in a socket.

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