0

In Python, is there any (proper) way to change the the default exception handling behaviour so that any uncaught exception will terminate/exit the program?

I don't want to wrap the entire program in a generic try-except block:

try:
    // write code here
except Exception:
    sys.exit(1)

For those asking for more specificity and/or claiming this is already the case, it's my understanding that not all Python exceptions are system-exiting: docs

Edit: It looks like I have forked processes complicating matters so won't be posting any specific details about my own mess.

If you're looking for an answer to the original question, Dmitry's comment is interesting and useful, references the 2nd answer to this question

Community
  • 1
  • 1
s-low
  • 706
  • 2
  • 8
  • 21

1 Answers1

0

You can use Specific exception instead of Exception because Exception is a Base class for all exceptions. For more details refer Exception tutorial

You can write your script like this-

try:
   # write code here
except OverflowError:
   raise SystemExit
except ArithmeticError:
   sys.exit()
except IOError:
   quit()

Try this different approaches to find what is exactly you are missing.

Edit 1 - Maintain Program Execution

In order to maintain your program execution try this one-

consider error_handler function is raising SystemExit exception then In your main method you need to add below code so you can maintain your program execution.

try:
   error_handler()
except SystemExit:
   print "sys.exit was called but I'm proceeding anyway (so there!-)."
ketan
  • 2,732
  • 11
  • 34
  • 80