20

What is the difference between calling sys.exit() and throwing an exception in Python?

Let's say I have a Python script which does the following:

  1. open a file
  2. read lines
  3. close it

If the file doesn't exist or an IOException gets thrown at runtime, which of the options below makes more sense?

  1. no except/catch of the exception, if exception occurs, it fails out (which is expected behaviour anyway)
  2. except/catch the exception, logs the error message, throw customized exception by myself, fails out.
  3. in an except IOException block, exit with an error message e.g. sys.exit("something is wrong")

Does option 3 kill the process while 1 and 2 do not? What's the best way to handle the Python exceptions given that Python doesn't have a checked exception like Java (I am really a Java developer ^_^)?

2 Answers 2

24

sys.exit raises a SystemExit itself so from a purely technical point of view there's no difference between raising that exception yourself or using sys.exit. And yes you can catch SystemExit exceptions like any other exception and ignore it.

So it's just a matter of documenting your intent better.

PS: Note that this also means that sys.exit is actually a pretty bad misnomer - because if you use sys.exit in a thread only the thread is terminated and nothing else. That can be pretty annoying, yes.

Sign up to request clarification or add additional context in comments.

Comments

13

There's a small, subtle difference:

import sys

try:
    sys.exit()
except:
    print("Caught")

that except statement catches the exception whereas:

import sys

try:
    sys.exit()
except Exception:
    print("Caught")

exits without error. SystemExit exception (like KeyboardInterrupt) isn't caught by except Exception, but caught by except alone.

So if the caller catches everything with except: (which is bad practice), your sys.exit won't quit but will be considered as an "error". That's why except Exception: is better to be sure to catch all exceptions except CTRL+C and system exit (which are of the BaseException class).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.