Python throws exceptions and custom exception raise

Use raise to throw an exception. When the program has an error, python will automatically raise an exception, or it can be explicitly raised through raise. Once the raise statement is executed, the statement following the raise cannot be executed.

try:
     s = None
     if s is None:
         print "s 是空对象"
         raise NameError     #如果引发NameError异常,后面的代码将不能执行
     print len(s)
except TypeError:
     print "空对象没有长度"

Custom exception python allows programmers to customize exceptions, which are used to describe exceptions that are not involved in python. Custom exceptions must inherit the Exception class. Custom exceptions end with "Error" according to the naming convention, which explicitly tells the programmer that this is an exception . Custom exceptions are raised using the raise statement and can only be triggered manually. Demo raise usage

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from __future__ import division
 
class DivisionException(Exception):
      def __init__(self, x, y):
            Exception.__init__ (self, x, y)       #调用基类的__init__进行初始化
            self.x = x
            self.y = y
 
if __name__ == "__main__":
      try:
            x = 3
            y = 2
      if x % y > 0:                               #如果大于0, 则不能被初始化,抛出异常
            print x/y
            raise DivisionException(x, y)
except DivisionException,div:                     #div 表示DivisionException的实例对象
      print "DivisionExcetion: x/y = %.2f" % (div.x/div.y)

Guess you like

Origin blog.csdn.net/qdPython/article/details/112612770
Recommended