hzk1211
hzk1211

Reputation: 3

In there anyway i can make my multiple exception into a new py file?

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

Answers (2)

0xInfection
0xInfection

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

tayler6000
tayler6000

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

Related Questions