python raise异常处理

python raise异常处理

一般最简单的异常处理是try  except:

try:
      f = open('test.txt')
except Exception as e:
      print(e)

finally:
      f.close()

自己也可以用raise自定义异常:

class CustomError(Exception):
def __init__(self, ErrorInfo): self.errorinfo = ErrorInfo def __str__(self): return self.errorinfo ============================================ try:
code.........code
code.........code
raise CustomError("xxxx") except CustomError as e: print(e)

自定义异常类需要继承自Exception类。
自定义异常类需要实现__str__方法来定义需要抛出的异常信息。
raise语句主动抛出异常。
捕获异常需要通过try...except 语句,其中"except"语句必须有用相同的异常(或者直接抛出Exception)来抛出类对象。

具体事例如下:

#1.用户自定义异常类型
class TooLongExceptin(Exception):

    def __init__(self,Leng):
        self.leng = Leng
    def __str__(self):
        print("姓名长度是"+str(self.leng)+",超过长度了")
#1.捕捉用户手动抛出的异常,跟捕捉系统异常方式一样
def name_Test():
    try:
        name = input("enter your naem:")
        if len(name)>4:
            raise TooLongExceptin(len(name))
        else :
            print(name)
 
    except TooLongExceptin,e_result:  #e_result是基于TooLongExceptin类创建的实例
     print("捕捉到异常了") print("打印异常信息:",e_result) #调用函数,执行 name_Test() ==========执行结果如下:================================================== enter your naem:aaafsdf 捕捉到异常了 Traceback (most recent call last): 打印异常信息: 姓名长度是7,超过长度了 姓名长度是7,超过长度了 File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 16, in name_Test raise TooLongExceptin(len(name)) __main__.TooLongExceptin: <exception str() failed> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 26, in <module> name_Test() File "D:/pythoyworkspace/file_demo/Class_Demo/extion_demo.py", line 22, in name_Test print("打印异常信息:",e_result) TypeError: __str__ returned non-string (type NoneType)
code.........code
原文地址:https://www.cnblogs.com/111testing/p/13905552.html