Carla
Carla

Reputation: 3380

Unable to system.exit within a try section

I'm trying to port an existing Java program I have. I have the following try section:

try:
    quote = getValue(i)
    writeData(i,quote)
except:
    print("Oops!", sys.exc_info()[0], "occurred.")

Within the getValue(value) function, under some conditions I want to exit the program:

sys.exit()

However, the except clause intercepts also this kind of error:

Oops! <class 'SystemExit'> occurred.

From my Java background a System.exit() forces the termination of the program. What is the simplest way in Python to force exiting the program, even with an except clause?

Upvotes: 0

Views: 455

Answers (3)

md2perpe
md2perpe

Reputation: 3071

The sys.exit() call does nothing more than raises a SystemExit exception. You are catching this.

You can handle that exception specifically and reraise it:

try:
    quote = getValue(i)
    writeData(i,quote)
except SystemExit:
    raise
except:
    print("Oops!", sys.exc_info()[0], "occurred.")

Upvotes: 1

chepner
chepner

Reputation: 531355

sys.exit just raises a SystemExit exception, which is a subclass of BaseException but not Exception.

>>> issubclass(SystemExit, Exception)
False
>>> issubclass(SystemExit, BaseException)
True
>>> issubclass(Exception, BaseException)
True

A base except catches all exceptions, equivalent to except BaseException, which is why you virtually never want to use a bare except. Use except Exception to only catch error-like exceptions, not flow-control exceptions as well.

try:
    quote = getValue(i)
    writeData(i,quote)
except Exception:
    print("Oops!", sys.exc_info()[0], "occurred.")

As a general rule, you want to limit your except clauses as much as possible. When doing something as broad as except Exception, you usually want to exit your program or re-raise the exception, not treat it as handled just by logging it.

Upvotes: 3

Cereaubra
Cereaubra

Reputation: 69

You could catch the SystemException and use the value to call sys.exit() again:

import sys

try:
    sys.exit(1)
except SystemExit as e:
    sys.exit(e.code)

Upvotes: 1

Related Questions