Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't catch SystemExit exception Python

Tags:

I am trying to catch a SystemExit exception in the following fashion:

try:
    raise SystemExit
except Exception as exception:
    print "success"

But, it doesn't work.

It does work however when I change my code like that:

try:
    raise SystemExit
except:
    print "success"

As far as I am aware, except Exception as exception should catch any exception. This is how it is described here as well. Why isn't that working for me here?

like image 626
Eugene S Avatar asked Oct 29 '14 04:10

Eugene S


People also ask

Can you catch SystemExit?

The SystemExit exception is inherited from this BaseException instead of Exception or StandardError as it is not any technical error so that it can be caught by the code that catches the exception. So when this exception is raised and if it cannot be handled then the Python interpreter exits.

What is SystemExit Python?

SystemExit is an exception, which basically means that your progam had a behavior such that you want to stop it and raise an error. sys. exit is the function that you can call to exit from your program, possibily giving a return code to the system.

How do you handle a sys exit exception?

Wrap your main code in a try / except block, catch SystemExit , and call os. _exit() there, and only there! This way you may call sys. exit normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and then calling os.


1 Answers

As documented, SystemExit does not inherit from Exception. You would have to use except BaseException.

However, this is for a reason:

The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.

It is unusual to want to handle "real" exceptions in the same way you want to handle SystemExit. You might be better off catching SystemExit explicitly with except SystemExit.

like image 103
BrenBarn Avatar answered Oct 02 '22 15:10

BrenBarn