I have seen a few examples like this , this and this , which show how to throw custom exception in 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.