user3776749
user3776749

Reputation: 697

How to efficiently exit a python program if any exception is raised/caught

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

Answers (4)

rassar
rassar

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

JacobIRR
JacobIRR

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

Moinuddin Quadri
Moinuddin Quadri

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

double_j
double_j

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

Related Questions