Python Exceptions and Error Handling
Learn how Python reports runtime failures, handles specific exceptions, performs cleanup, raises errors deliberately, and defines custom exceptions.
Basic
Programs do not always succeed every time. A file can contain valid Python syntax and still encounter a problem while it runs. Python represents these runtime problems with
exceptions. Learning to read, handle, and deliberately raise exceptions helps your programs respond to expected failures without hiding unexpected bugs.
Syntax errors and exceptions
A
SyntaxError means Python cannot parse the code as a valid program. An exception is different: the code can be syntactically valid, but an operation fails while the program is running.
print(10 / 0)This code is syntactically valid, but running it raises ZeroDivisionError.
The exception type tells you what kind of problem occurred. Python also reports a traceback showing where the exception propagated through the program.
Handle a specific exception
Use
try and
except when you know a failure can be handled meaningfully. Put the operation that may fail in the try block, then handle the specific exception you expect.
try:
number = int(input("Enter a whole number: "))
except ValueError:
print("Please enter a whole number.")ValueError is handled only for the conversion that can fail.
Prefer a specific exception type instead of catching
Exception broadly. Unexpected failures should normally remain visible so they can be fixed rather than silently disguised.
Multiple handlers
A single
try statement can have more than one
except clause. Python selects the first matching handler. Put more specific exception types before broader ones when their relationship requires it.
try:
value = int(input("Number: "))
result = 100 / value
except ValueError:
print("That was not an integer.")
except ZeroDivisionError:
print("Zero is not allowed here.")Different failures can receive different responses.
The else clause
A
try statement may include
else. The else block runs only when the try block completes without raising an exception. It is useful for keeping success-path code outside the protected operation.
try:
number = int(input("Number: "))
except ValueError:
print("Invalid number.")
else:
print("You entered", number)The else block runs only after a successful conversion.
Always clean up with finally
Use
finally for cleanup that must happen whether an exception occurred or not. This is especially useful when a resource needs to be released. For resources that support it, Python also provides the
with statement, which we will study separately.
try:
print("work")
finally:
print("cleanup")finally runs whether the try block succeeds or raises an exception.
Raise an exception
Programs can deliberately signal invalid input or an invalid state with
raise. Raising a specific exception communicates what went wrong to the code that can handle it.
def require_positive(number):
if number <= 0:
raise ValueError("number must be positive")
return numberThe function rejects an invalid value by raising ValueError.
Define your own exception
When a program has a meaningful domain-specific failure, you can define an exception class derived from
Exception. Keep custom exceptions focused on communicating the kind of failure; they can carry additional information when needed.
class InvalidScoreError(Exception):
pass
def set_score(score):
if not 0 <= score <= 100:
raise InvalidScoreError("score must be between 0 and 100")
return scoreA custom exception gives callers a precise failure type to handle.
Do not hide unexpected failures
Good exception handling has a boundary. Handle failures you can recover from or explain, and let unexpected exceptions propagate. Catching every exception merely to print a generic message can make real programming errors much harder to diagnose.
Python also supports exception chaining when one failure is deliberately translated into another. Exception groups and
except* are taught in the dedicated Exception Groups and except* lesson.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.