Reputation: 3
I am new to python and still learning about it. Is there any way I can modularize all the exception by making the multiple exception into 1 new python file? Below is my code.
class hypeaf:
def hi():
4/0
if __name__ == "__main__":
try:
h=hypeaf
h.hi()
except ZeroDivisionError:
print("zero")
except FileNotFoundError:
print("one")
except FileExistsError:
print("two")
except Exception:
print("three")
Upvotes: 0
Views: 63
Reputation: 2919
If I correctly understand your question, you can do something like this:
Have your main code in code.py
with contents:
from exceptions import HandleExceptions
a = 5
try:
if a/0 == 2:
print('divided by zero') # obviously won't reach here
except Exception as e:
HandleExceptions(e)
And have a exceptions.py
with the following:
def HandleExceptions(x):
if isinstance(x, ZeroDivisionError):
print('Dividing by zero not allowed')
if isinstance(x, FileNotFoundError):
print('File not found')
...
I hope this solves the problem.
Upvotes: 2
Reputation: 101
I think I understand what you mean. If you're saying you want to only handle errors in a separate file to help make your code easier to read then you should be able to do the following:
Main.py:
from ErrorHandling import ErrorHandler
class hypeaf:
def hi():
4/0
if __name__ == "__main__":
try:
h=hypeaf
h.hi()
except Exception as e:
ErrorHandler(e)
ErrorHandling.py:
def ErrorHandler(e):
try:
raise e
except ZeroDivisionError:
print("zero")
except FileNotFoundError:
print("one")
except FileExistsError:
print("two")
except Exception:
print("three")
Upvotes: 0