Difference between calling sys.exit () and throwing exception

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

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

  • open file
  • reading lines
  • close it

If the file does not exist or an IOException occurs at runtime, which of the following options makes sense?

  • no except / catch exceptions, if an exception occurs, it crashes (which is equivalent to the expected behavior)
  • to exclude / catch an exception, register an error message, independently discard an individual exception.
  • in the except IOException block except IOException , exit with an error message, for example. sys.exit("something is wrong")

Does option 3 include the process, but 1 and 2 do not? What is the best way to handle Python exceptions, given that Python does not have a checked exception like Java (I'm really a Java developer ^ _ ^)?

+8
source share
2 answers

sys.exit raises SystemExit itself, so from a purely technical point of view there is no difference between raising this 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: Please note that this also means that sys.exit is actually a pretty bad wrong name, because if you use sys.exit in a stream, the stream stops and nothing else. It can be quite unpleasant, yes.

+14
source

There is a slight, subtle difference:

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

that the except operator catches the exception, whereas:

import system

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

comes out without errors. A SystemExit exception (e.g. KeyboardInterrupt ) is not a SystemExit , except Exception , but except is executed alone.

Therefore, if the caller catches everything except: (which is bad practice), your sys.exit will not exit, but will be considered an “error” (therefore, except Exception: it’s better to make sure that it catches all except CTRL + C and exit systems (which belong to the BaseException class).

+2
source

Source: https://habr.com/ru/post/916896/


All Articles