Hacker News new | past | comments | ask | show | jobs | submit login

TIL SystemExit and that `sys.exit` actually raises SystemExit.

From Python docs: https://docs.python.org/3/library/exceptions.html#SystemExit

> exception SystemExit

> This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to sys.exit(). If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one. > A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to os.fork()).

Replying to your comment regarding:

> Isn't raise for "throwing" exceptions/errors though?

Well, some would argue that is idiomatic in python. A quick google search not only autocompletes "exceptions for control flow" to "exceptions for control flow python", but on the second search, most results discuss that (with many agreeing). I guess you can say most python developer wouldn't immediately assume it's an error. I definitely can say, I don't.




Right. In Python, raising an exception is considered just as safe and normal as returning a value, so Python uses exceptions even for very common things like stopping iterations. IMHO a Python exception is quite similar to a Rust "Result::Err".




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: