Ben*_*min 1 python error-handling python-module
我正在制作一个小型Python模块.我想要这个模块返回错误,如果有的话.在Python中创建错误对象的正确或标准方法是什么?
编辑:我不确定如何创建自己的错误,当然因为我不确定错误是如何工作的(我只知道如何捕获它们try: ... except: ...
).所以现在我做了草稿错误消息,错误是字符串.当出现意外情况时,我会打印和return None
.我猜这不是正确的方法:)
例:
...
self.IsNotStringError = "Args was not a string."
...
def myMethod(self, args)
""" Args must be a string. """
if not isinstance(args, str):
print IsNotStringError
return None
else:
do things...
Run Code Online (Sandbox Code Playgroud)
编辑(之二):在阅读下面的答案后,我进一步研究了Python文档.有一个关于如何制作用户定义的异常的教程.
文档中的示例:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
Run Code Online (Sandbox Code Playgroud)
您可以通过继承来创建自己的异常类Exception
:
class YourError( Exception ): pass
Run Code Online (Sandbox Code Playgroud)
接下来只需在需要时提高它:
raise YourError("error message")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2535 次 |
最近记录: |