Python try / except
Learn how to handle exceptions safely using
try, except, and
else so your Python programs can
respond gracefully when something goes wrong.
Learning Objectives
By the end of this lesson, you will understand how Python handles exceptions and how to prevent expected errors from crashing your program.
You will learn how to:
- Understand exceptions and exception handling.
- Use
tryandexcept. - Handle specific exception types.
- Handle multiple exceptions.
- Access exception information using
as. - Use the
elseblock. - Handle errors in user input and file operations.
- Write clear and useful error messages.
- Avoid common exception-handling mistakes.
What Is Exception Handling?
An exception is an event that occurs while a Python program is running and interrupts the normal flow of execution.
For example, converting the text
"hello" into an integer is not valid:
number = int("hello")
ValueError: invalid literal for int()
If an exception is not handled, Python normally stops the current program and displays a traceback.
Instead of crashing immediately, your program can respond appropriately to expected problems.
Why Use try / except?
Real-world programs interact with users, files, databases, networks, APIs and external systems. These operations can fail for many reasons.
For example:
- A user enters letters instead of a number.
- A file does not exist.
- A calculation attempts division by zero.
- A dictionary key does not exist.
- A value has an unexpected type.
Exception handling allows you to decide what your program should do when these situations occur.
Exception handling is not about pretending errors do not exist. It is about handling predictable failures deliberately.
Basic try / except Syntax
The basic structure is:
try:
# Code that might cause an exception
risky_code()
except:
# Code that handles the exception
handle_error()
Python first executes the code inside
try.
If an exception occurs, Python looks for a matching
except block.
- Enter the
tryblock. - Run the code.
- If no exception occurs, continue normally.
- If an exception occurs, find a matching
except. - Execute the matching handler.
Handling a Specific Exception
Good Python programs usually catch the specific exception they expect.
try:
age = int("abc")
except ValueError:
print("Invalid age.")
Invalid age.
This is better than catching every possible exception because the program clearly communicates what problem it knows how to handle.
Handling ValueError
ValueError commonly occurs when a function
receives a value of the correct general type but the
value itself is inappropriate.
A common example is converting invalid text to an integer.
try:
number = int("python")
print(number)
except ValueError:
print("Please provide a valid integer.")
Please provide a valid integer.
This pattern is extremely useful when working with user input.
Handling ZeroDivisionError
Python raises ZeroDivisionError when you
attempt to divide a number by zero.
try:
result = 100 / 0
print(result)
except ZeroDivisionError:
print("Cannot divide by zero.")
Cannot divide by zero.
Handle the error with a meaningful response instead of silently ignoring it.
Multiple except Blocks
A single try block can have multiple
except blocks.
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Number cannot be zero.")
Python checks the exception handlers until it finds one that matches the exception.
Different errors can receive different, meaningful responses.
Handling Multiple Exceptions Together
Sometimes different exceptions should receive the same response.
You can group exception types inside a tuple.
try:
value = int("hello")
except (ValueError, TypeError):
print("Invalid input.")
This is useful when different exceptions have the same handling logic.
Use parentheses around multiple exception types:
(ValueError, TypeError).
The Exception Object with as
You can store the exception object in a variable using
the as keyword.
try:
number = int("abc")
except ValueError as error:
print("Error:", error)
The variable error contains information
about the exception.
Error: invalid literal for int() with base 10: 'abc'
Exception objects are particularly useful for debugging, logging and producing informative messages.
The else Block
Python allows an else block after
except.
The else block runs only when the
try block finishes without an exception.
try:
number = int("25")
except ValueError:
print("Invalid number.")
else:
print("Number:", number)
Number: 25
try = attempt something,
except = handle failure,
else = continue after success.
try / except / else
These three blocks can work together to make the structure of a program clearer.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("You entered:", number)
If the conversion fails, Python executes
except.
If the conversion succeeds, Python executes
else.
Keep the try block focused on the
operation that can actually raise the exception.
Nested try / except
A try / except block can exist inside
another try block.
try:
print("Outer operation")
try:
number = int("abc")
print(number)
except ValueError:
print("Inner error handled.")
except Exception:
print("Outer error handled.")
Outer operation Inner error handled.
Deeply nested exception handling can make a program difficult to understand. Prefer a simple structure whenever possible.
Practical User Input Example
One of the most common uses of try / except
is validating user input.
try:
number = int(input("Enter a number: "))
print("Your number is:", number)
except ValueError:
print("Please enter a valid integer.")
Without exception handling, entering something like
hello would cause the program to stop.
With exception handling, the program can give the user a helpful message.
Input validation is essential in forms, calculators, registration systems, dashboards and command-line applications.
File Handling with try / except
Files may not exist, may be inaccessible, or may have permission problems.
Exception handling can make file operations safer.
try:
with open("students.txt", "r", encoding="utf-8") as file:
data = file.read()
except FileNotFoundError:
print("The file was not found.")
else:
print(data)
This is useful when working with configuration files, reports, logs, student records and application data.
FileNotFoundErrorPermissionErrorIsADirectoryError
Expected vs Unexpected Errors
Not every error should be handled in the same way.
Expected Problems
These are situations your program can reasonably anticipate.
- Invalid user input
- Missing file
- Division by zero
- Invalid conversion
Unexpected Problems
These may indicate a programming bug or a system-level problem that needs investigation.
If your program has a programming mistake, silently catching the exception can make debugging much harder.
A good rule is to catch exceptions when you know how to handle them meaningfully.
Writing Good Error Messages
An error message should help the user understand what happened and, when possible, what to do next.
except ValueError:
print("Please enter your age as a whole number.")
Compare that with:
except ValueError:
print("Error.")
- Clear
- Specific
- Relevant
- Helpful
- Easy for the intended user to understand
Common try / except Mistakes
1. Using a bare except:
This catches almost everything and can hide problems.
try:
risky_code()
except:
pass
2. Catching Exception for everything
except Exception: can be useful in certain
application-level boundaries, but it should not become
a replacement for understanding specific failures.
3. Using an empty exception handler
Silently ignoring an exception can make debugging extremely difficult.
4. Putting too much code inside try
Keep the try block focused on the operation
that might actually fail.
5. Using exceptions to control normal program flow
Exceptions should generally represent exceptional situations, not ordinary decisions that could be handled with normal conditions.
Practice Exercises
Try these exercises yourself before looking for a solution.
Exercise 1 — Safe Integer Conversion
Ask the user for a value and safely convert it to an integer.
Exercise 2 — Safe Division
Ask for two numbers and handle division by zero.
Exercise 3 — Multiple Exceptions
Create a program that handles both
ValueError and
ZeroDivisionError.
Exercise 4 — Exception Message
Catch a ValueError and display the
actual exception message using as.
Exercise 5 — Use else
Ask for a number and use else to print
the number only when conversion succeeds.
Exercise 6 — Safe File Reading
Try to open a text file and handle
FileNotFoundError.
Exercise 7 — Calculator Validation
Build a calculator that safely handles invalid numbers and division by zero.
Mini Challenge — Safe Calculator
Build a calculator that does not crash when the user enters invalid data.
- Ask for the first number.
- Ask for the second number.
- Ask for an operator.
- Support
+,-,*and/. - Handle invalid number input.
- Handle division by zero.
- Handle unsupported operators.
- Display the result when successful.
Starter Structure
try:
first = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
second = float(input("Enter second number: "))
if operator == "+":
result = first + second
elif operator == "-":
result = first - second
elif operator == "*":
result = first * second
elif operator == "/":
result = first / second
else:
print("Unsupported operator.")
except ValueError:
print("Please enter valid numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)
Improve the calculator so that it keeps asking for calculations until the user chooses to exit.
Quick Knowledge Check
Test your understanding of try / except.
1. Which block contains code that might raise an exception?
2. Which exception is commonly raised by int("hello")?
3. Which exception occurs when dividing by zero?
4. What does the else block do?
5. What does except ValueError as error do?
6. Which approach is generally better?
7. What is a major problem with silently ignoring exceptions?
8. Which exception is appropriate for a missing file?
9. Can multiple exception types be handled together?
10. What is the main purpose of exception handling?
Lesson Summary
In this lesson, you learned how Python uses
try / except to handle exceptions.
try contains code that may raise
an exception.
except handles matching exceptions.
except blocks can handle
different problems.
as.
else runs when the
try block succeeds.
Good exception handling makes programs more reliable, user-friendly and easier to maintain. Catch the problems you know how to handle, handle them clearly, and allow genuine bugs to remain visible during development.
You've reached the end!
If you understand try,
except, specific exceptions and
else, you're ready to move deeper
into Python's error-handling system.