Reputation: 697
Say I have a block of exception statements:
try:
expression
except err1:
#process error
...
...
except err10:
#process error
and I want to call sys.exit(1)
if ANY of the exceptions are raised. Do I have to call it manually in every single sub-block or is there a built in way to have a statement akin to:
...
except err10:
#process error
"if any of these exception were raised":
sys.exit(1)
Upvotes: 4
Views: 11139
Reputation: 5660
One thing you could do is:
flag = False
try:
expression
flag = True
except err1:
#process error
...
...
except err10:
#process error
if not flag:
sys.exit(1) #exit program
If the flag is False, that means that you didn’t pass through the try
loop, and so an error was raised.
Upvotes: 8
Reputation: 8946
Here's what I was talking about in my comment:
isok = False
try:
#try to do something
isok = True
except err1:
#do something besides raising an exception
except err5:
#do something besides raising an exception
if not isok:
raise SystemExit
Upvotes: 3
Reputation: 48057
In Python, there is an optional else
block which is executed in case no exception is raised. You may use this to set a flag for you code and exit the code out of the try/except
block as:
is_exception = True
try:
expression
except err1:
# ... something
except err10:
# ... something else
else:
# This will be executed if there is no exception
is_exception = False
if is_exception:
sys.exit(1)
Upvotes: 4
Reputation: 1706
raised = True
try:
expression
except err1:
# process error
raise
...
except err10:
# process error
raise
else:
# if no error was raised
raised = False
finally:
if raised:
raise SystemExit
Upvotes: 3