To handle runtime errors in Python, wrap the risky code in a try block, catch the specific exception types you expect in except clauses, and use else and finally for the success path and cleanup. Let unexpected errors propagate or log them with logging.exception instead of hiding them.
A runtime error is an exception raised while the program runs, such as ZeroDivisionError, FileNotFoundError, TypeError or ValueError. Unlike a syntax error, it is not detected before execution, and an unhandled exception ends the program with a traceback.
| Exception | Typical cause |
|---|---|
ZeroDivisionError | Dividing by zero |
FileNotFoundError | Opening a path that does not exist |
TypeError | An operation on the wrong type, such as "a" + 1 |
ValueError | The right type with an invalid value, such as int("abc") |
KeyError | Reading a missing dictionary key |
IndexError | Using a list index out of range |
AttributeError | Accessing an attribute that does not exist |
All of these inherit from Exception, so you can catch them individually or as a group.
The full form has four parts. The try block holds the code that may fail, except handles specific errors, else runs only when no exception happened, and finally always runs.
Keep the try block as small as possible so you do not catch errors from unrelated lines. Several exception types can share one handler with a tuple: except (KeyError, IndexError):.
except Exception as e: is acceptable at the outer edge of a program, such as a request handler, where you log the error and continue. Inside normal logic it hides bugs. Never use a bare except:, because it also catches KeyboardInterrupt and SystemExit.
Raise an exception when a function receives input it cannot handle. Choose a built-in type that fits, and write a message that says what was wrong.
When you translate a low-level error into a higher-level one, chain it with from so the original cause stays visible.
For a library or application, define your own exception hierarchy so callers can catch your errors precisely.
Name classes with an Error suffix and inherit from Exception, not BaseException.
Report errors through the logging module so they reach files or monitoring tools. Inside an except block, logger.exception records the message and the traceback.
To debug, read the traceback from the bottom up: the last line names the error and the line above it shows where it was raised. Use python -m pdb script.py or breakpoint() to inspect state. Since Python 3.11, tracebacks mark the exact failing expression, and exception.add_note("extra context") attaches extra details to an error.
A syntax error is found when Python parses the file, before any code runs. A runtime error occurs during execution and can be handled with try and except.
Yes, when you want code to run only if the try block succeeded. It keeps the protected block small and avoids catching errors from the follow-up code.
Use contextlib.suppress(FileNotFoundError) for a specific, expected error. Avoid except: pass, which silently hides every problem.
Python favours trying the operation and handling the exception, known as EAFP. Checking first can introduce race conditions, for example when a file is deleted between the check and the open.
Handle runtime errors by catching specific exceptions around small try blocks, use else and finally for clean control flow, raise clear errors yourself, chain causes with from, and log with logger.exception. Reserve broad handlers for the edges of your program.