Python exception inheritance and implement custom exception code examples

This article describes the Python exception inheritance and implement custom exception code examples, sample code by text describes in great detail, has a certain reference value of learning for all of us to learn or work, a friend in need can refer

Introduces the inheritance of abnormal python, and how custom exception

  1. Unusual inheritance BaseException # base class for all exceptions
+-- SystemExit # 解释器请求退出
 +-- KeyboardInterrupt  用户中断执行(通常是输入^C)
 +-- GeneratorExit # 生成器(generator)发生异常来通知退出
 +-- Exception # 常规异常的基类
  +-- StopIteration # 迭代器没有更多的值
  +-- StandardError # 标准错误
  | +-- BufferError
  | +-- ArithmeticError
  | | +-- FloatingPointError
  | | +-- OverflowError
  | | +-- ZeroDivisionError
  | +-- AssertionError
  | +-- AttributeError
  | +-- EnvironmentError
  | | +-- IOError
  | | +-- OSError
  | |   +-- WindowsError (Windows)
  | |   +-- VMSError (VMS)
  | +-- EOFError
  | +-- ImportError
  | +-- LookupError
  | | +-- IndexError
  | | +-- KeyError
  | +-- MemoryError
  | +-- NameError
  | | +-- UnboundLocalError
  | +-- ReferenceError
  | +-- RuntimeError
  | | +-- NotImplementedError
  | +-- SyntaxError
  | | +-- IndentationError
  | |   +-- TabError
  | +-- SystemError
  | +-- TypeError
  | +-- ValueError
  |   +-- UnicodeError
  |    +-- UnicodeDecodeError
  |    +-- UnicodeEncodeError
  |    +-- UnicodeTranslateError
  +-- Warning
   +-- DeprecationWarning
   +-- PendingDeprecationWarning
   +-- RuntimeWarning
   +-- SyntaxWarning
   +-- UserWarning
   +-- FutureWarnin
   +-- ImportWarnin
   +-- UnicodeWarnin
   +-- BytesWarning
  1. Custom exception
#自定义异常 需要继承Exception
class MyException(Exception):
 
 def __init__(self, *args):
  self.args = args
 
if __name__ == '__main__':
 try:
  raise MyException("自定义异常")
 except MyException as e:
  print e
  1. Exception trap
# 示例
str1 = 'abc'
try:
 int(str1)
except IndexError as e:
 print e
except KeyError as e:
 print e
except ValueError as e:
 print e
else:
 print 'try内正常处理'
finally:
 print '无论异常与否,都会执行我'
  1. Active trigger abnormal
# raise xxx
def test_zero(num):
 try:
  if num == 0:
   raise ValueError('参数错误')
  return num
 except Exception as e:
  print e
 
test_zero(0)
  1. View abnormalities using traceback module

When an exception occurs, Python can "remember" the current state of exception that was thrown and the program.
Python maintains traceback (tracking) object that contains information about the function call stack when an exception occurs.
Abnormalities may be caused in a series of nested function calls deeper in.
When the program calls each function, Python will insert the function name in the "function call stack" at the beginning. Once the exception is raised, Python will search for an appropriate exception handler. If the current function is no exception handler, the current function terminates execution, Python will search the current caller of the function, and so on, until a match is found exception handler, or Python arrive until the main program. The find suitable exception handler is called a "stack removed to open the solution" (StackUnwinding).
Interpreter maintains information on the one hand and place the stack of related functions, it also maintains information from the stack function "flounder open solutions" related.

#示例
def div(num1, num2):
 try:
  result = num1/num2
  return result
 except Exception as e:
  traceback.print_exc()
 
print div(1, 0)
#执行结果
Traceback (most recent call last):
None
 File "F:/Technology-20161005/python/python_project/demo/exceptiondemo/exceptiondemo.py", line 17, in div
 result = num1/num2
ZeroDivisionError: integer division or modulo by zero
# 可以将异常信息写到文件中
traceback.print_exc(file=open('1.txt','w+'))

Finally, I recommend a good reputation python gathering [ click to enter ], there are a lot of old-timers learning skills, learning experience

, Interview skills, workplace experience and other share, the more carefully prepared the zero-based introductory information, information on actual projects, programmers every day

Python method to explain the timing of technology, to share some of the learning and the need to pay attention to small details

Published 48 original articles · won praise 21 · views 60000 +

Guess you like

Origin blog.csdn.net/haoxun11/article/details/105081866