[英]Throw custom exception in Python with input parameters to print
I have seen a few examples like this , this and this , which show how to throw custom exception in Python. 我已经看到了几个类似this , this和this的示例,它们展示了如何在Python中引发自定义异常。 But what I'm hoping to accomplish is something like this:
但是我希望完成的事情是这样的:
## in main.py
import my_errors
if os.path.exists(filename):
# here, I'd like to pass in 'filename' as parameter to FileNotFound
raise my_errors.FileNotFound(filename)
## in my_errors.py
class MyError(Exception):
pass
class FileNotFound(MyError):
# here, how do I make this FileNotFound class to accept/receive 'filename' as parameter so that I can print something informative like below
print("FileNotFound ERROR: Please make sure that the following file exists:", filename)
Thank you in advance for your help! 预先感谢您的帮助!
You'll want to implement your own __init__()
function. 您将要实现自己的
__init__()
函数。
class FileNotFound(MyError):
def __init__(self, filename):
super().__init__("FileNotFound ERROR: Please make sure that the following file exists:" % filename)
Note that this will set the error message of the exception. 请注意,这将设置异常的错误消息。 To print normally:
正常打印:
class FileNotFound(MyError):
def __init__(self, filename):
print("FileNotFound ERROR: Please make sure that the following file exists:", filename)
super().__init__(filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.