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?
>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.