0

自定义异常为什么不从BaseException继承

 2 years ago
source link: https://www.mindg.cn/?p=2873
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

自定义异常为什么不从BaseException继承

自定义一个异常需要继承Exception类或子类,虽然BaseException是Exception的父类,但如果继承BaseException可能会导致捕获不到自定义的异常,来看个例子:

class MyError(BaseException):
raise MyError
except Exception:
print('---my error---')

y运行这段代码会进行报错,没有捕获到我们自定义的异常,改成继承Exception就可以正常捕获了,如下:

class MyError(Exception):
raise MyError
except Exception:
print('---my error---')
### resulut###
---my error---

自定义错误信息:

class MyError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
raise MyError('我的自定义错误')
except Exception as e:
print(e)

就是在初始化的时候传入错误内容, 然后实例化这个类, 这个e就是实例化后的对象,之所以能显示错误信息是因为定义了__str__方法,对象以字符串形式显示。

本条目发布于2022-01-08。属于Python分类。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK