Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading