Errors are part of normal programming. Some errors are syntax problems that prevent the file from running; others happen while the program executes.
Reading a traceback#
number = int("abc")Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'abc'
Read the last line first: it names the exception and gives a short explanation. The lines above show the call path. In ILoveCompiler, the Errors panel presents the traceback with the same information.
Catching exceptions#
text = input("Enter a number: ")
try:
number = int(text)
except ValueError:
print("That is not a whole number.")
else:
print(f"Doubled: {number * 2}")- The
tryblock contains code that may fail. except ValueErrorhandles only that exception type.elseruns when no exception occurred.finallyalways runs, whether or not an exception was raised.
Catch specific exceptions. A bare except: also catches KeyboardInterrupt and SystemExit, which usually should not be swallowed.
try:
value = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Multiple except blocks#
try:
number = int(input())
result = 100 / number
except ValueError:
print("Please enter a whole number")
except ZeroDivisionError:
print("The number cannot be zero")Python checks the handlers in order and runs the first matching one.
You can capture the exception object:
try:
number = int("abc")
except ValueError as error:
print("Conversion failed:", error)Use the message for logging or diagnostics. Do not display raw technical details to end users unless the context is appropriate.
Raising exceptions#
When a function receives invalid input, raise an exception instead of returning a misleading value:
def set_age(age):
if not isinstance(age, int):
raise TypeError("age must be an integer")
if age < 0 or age > 150:
raise ValueError("age must be between 0 and 150")
return ageThe caller can handle these errors:
try:
set_age(200)
except ValueError as error:
print(error)age must be between 0 and 150
finally for cleanup#
finally is useful when a resource must be released:
def read_first_line(path):
file = open(path, encoding="utf-8")
try:
return file.readline().strip()
finally:
file.close()The file closes even if reading raises. For most file work, a with statement is shorter and safer:
with open("notes.txt", encoding="utf-8") as file:
first_line = file.readline().strip()The context manager closes the file automatically, including when an exception occurs.
Custom exceptions#
Larger programs define exception classes to represent domain failures:
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough funds")
return balance - amountA specific class lets callers distinguish this failure from unrelated errors.
Practice#
Write a program that repeatedly asks for two integers and prints their quotient. Handle ValueError and ZeroDivisionError separately. Add a finally block that prints "Attempt finished". Then write a function that raises ValueError when a score is outside 0 to 100.
