Is there any way where we can store the user defined exceptions (our customized exceptions) in a list? So that if any other exception occurs, which is not in list.. the program should simply be aborted.
Asked
Active
Viewed 45 times
2 Answers
2
A single except
can have multiple errors, custom or otherwise:
>>> class MyError(Exception):
pass
>>> try:
int("foo") # will raise ValueError
except (MyError, ValueError):
print "Thought this might happen"
except Exception:
print "Didn't think that would happen"
Thought this might happen
>>> try:
1 / 0 # will raise ZeroDivisionError
except (MyError, ValueError):
print "Thought this might happen"
except Exception:
print "Didn't think that would happen"
Didn't think that would happen

jonrsharpe
- 115,751
- 26
- 228
- 437
2
The usual way to do this is with an exception hierarchy.
class OurError(Exception):
pass
class PotatoError(OurError):
pass
class SpamError(OurError):
pass
# As many more as you like ...
Then you just catch OurError
in the except block, rather than trying to catch a tuple of them or having multiple except blocks.
Of course, nothing actually prevents you from storing them in a list like you mention:
>>> our_exceptions = [ValueError, TypeError]
>>> try:
... 1 + 'a'
... except tuple(our_exceptions) as the_error:
... print 'caught {}'.format(the_error.__class__)
...
caught <type 'exceptions.TypeError'>

wim
- 338,267
- 99
- 616
- 750
-
In this case what I wish to achieve is if it's ValueError or TypeError 'ONLY THEN' I want to report the respective error message. For rest of all errors, I simply want to perform exit(1). I'm trying to figure out the way to do that. – NikAsawadekar Aug 15 '14 at 14:44
-
an unhandled exception would already do that (die). if you want to customise the "crash" behaviour, you can add another bare `except:` block and `sys.exit()` or whatever – wim Aug 15 '14 at 14:50