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:
- open a file
- read lines
- close it
If the file doesn’t exist or an IOException gets thrown at runtime, which of the options below makes more sense?
- no except/catch of the exception, if exception occurs, it fails out (which is expected behaviour anyway)
- except/catch the exception, logs the error message, throw customized exception by myself, fails out.
- in an
except IOExceptionblock, 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 ^_^)?
sys.exitraises aSystemExititself so from a purely technical point of view there’s no difference between raising that exception yourself or usingsys.exit. And yes you can catchSystemExitexceptions 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.exitis actually a pretty bad misnomer – because if you usesys.exitin a thread only the thread is terminated and nothing else. That can be pretty annoying, yes.