Reputation: 341
I got this piece of code that is catching an error. Is it possible to write the error handling inside a function for example and then just reference to it inside the code? The goal would be to have all the error handling in a separate file and just call the class inside the code when needed.
This is the normal way and its working fine
#!/usr/bin/env python3
def main():
try:
x = int("foo")
except ValueError:
print("I cought a ValueError")
if __name__ == '__main__': main()
I would like to try something like this, but is something like this possible? and how is it done in a proper way?:
#!/usr/bin/env python3
#All the error handeling goes here:
def exceptValueError():
except ValueError:
print("I cought a ValueError")
def exceptZeroDivisionError():
except ZeroDivisionError:
print("You cant devide by zero")
#Code goes here
def main():
try:
x = int("foo")
exeptValueError()
if __name__ == '__main__': main()
This gives me:
except ValueError:
^
SyntaxError: invalid syntax
Is it possible to use try and instead of except use a function that contains an except? I assume that is not really possible.
Upvotes: 0
Views: 53
Reputation: 106
def exeptValueError():
except ValueError:
print("I cought a ValueError")
This won't work because there is no try block before the except block (the try block in main doesn't count).
You could do the following, which would still be close to what you want
def exceptValueError():
print("I caught a ValueError")
def main():
try:
x = int("foo")
except ValueError:
exceptValueError()
Upvotes: 1