Python Advanced (27) – Custom Exceptions, Exceptions and Functions, Obtain Exception Information

Original link: https://chegva.com/5472.html

◎Knowledge points

  1. custom exception

  2. exceptions and functions

  3. Get exception information

◎Script practice

Custom exception

 """ Although python's built-in exception class objects can meet most of our needs, sometimes we may want to create custom exception class objects. Just as the base class of all built-in exception class objects is Exception, custom exception class objects only need to inherit Exception or its subclass """  class MyException(Exception): def __init__(self, msg1, msg2): self.msg1 = msg1 self.msg2 = msg2  try: raise MyException("123", "abc") except MyException as err: print(err) 

Exceptions and functions

 """ When an exception occurs in a function, the exception instance object will be thrown to the caller of the function. If the caller of the function does not catch and handle it, Then it will continue to be thrown to the caller of the upper layer, so that it will be thrown upwards, and finally it will be captured by the python interpreter. """  """ def f1(): print(1 / 0)  def f2(): f1()  def f3(): f2()  f3() """  """ In the process of the exception instance object being thrown upwards, the exception instance object can be selected to be captured and processed at a suitable layer, instead of being captured and processed at each layer. """  def f1(): print(1 / 0)  def f2(): f1()  def f3(): try: f2() except ZeroDivisionError as err: print(err)  f3() 

▽ Get exception information

 """ After the exception instance object is captured, the function exc_info in the standard library module sys can be called to obtain the relevant information of the exception. The return value of this function is a tuple containing three elements, which represent: The type of the exception, the error message of the exception, and the Traceback object containing the traceback information of the exception call stack To further extract the information contained in the Traceback object, you can call the function extract_tb() in the standard library module traceback """  import sys import traceback  def f1(): print(1 / 0)  def f2(): try: f1() except ZeroDivisionError: ex_type, ex_value, ex_traceback = sys.exc_info()  print('Exception type: %s' % ex_type) print('Exception error message: %s' % ex_value) print('Exception call stack traceback: %s' % ex_traceback)  tb = traceback.extract_tb(ex_traceback) print(tb)  for filename, linenum, funcname, source in tb: print('File name: %s' % filename) print('Number of lines: %s' % linenum) print('Function name: %s' % funcname) print('Source: %s' % source)  f2()

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/custom_exception.py

This article is reprinted from: https://chegva.com/5472.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment