繁体   English   中英

在Python中使用输入参数抛出自定义异常以进行打印

[英]Throw custom exception in Python with input parameters to print

我已经看到了几个类似thisthisthis的示例,它们展示了如何在Python中引发自定义异常。 但是我希望完成的事情是这样的:

## 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)

预先感谢您的帮助!

您将要实现自己的__init__()函数。

class FileNotFound(MyError):

    def __init__(self, filename):
        super().__init__("FileNotFound ERROR: Please make sure that the following file exists:" % filename)

请注意,这将设置异常的错误消息。 正常打印:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM