Panic in Python
In Python, we typically use exceptions to handle unexpected errors or situations. The equivalent of a panic in Python is raising an exception. Here’s an example:
import os
def main():
# We'll use exceptions throughout this site to check for
# unexpected errors. This is the only program on the
# site designed to raise an exception.
raise Exception("a problem")
# A common use of exceptions is to abort if a function
# returns an error value that we don't know how to
# (or want to) handle. Here's an example of
# raising an exception if we get an unexpected error when creating a new file.
try:
with open("/tmp/file", "w") as f:
pass
except IOError as e:
raise Exception(f"Couldn't create file: {e}")
if __name__ == "__main__":
main()
Running this program will cause it to raise an exception, print an error message and traceback, and exit with a non-zero status.
When the first exception in main
is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first raise
statement.
$ python panic.py
Traceback (most recent call last):
File "panic.py", line 13, in <module>
main()
File "panic.py", line 6, in main
raise Exception("a problem")
Exception: a problem
Note that in Python, it’s idiomatic to use exceptions for handling many errors, unlike some languages which might use error-indicating return values. Python’s try
/except
blocks allow for more granular error handling and recovery.
The Python equivalent of a panic (raising an exception) can be caught and handled using try
/except
blocks, allowing for more flexible error handling compared to Go’s panic which typically leads to program termination.