Home Course Roadmap
Home / Python Course / Lesson 40
Lesson 40 Error Handling

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.

45–55 minutes Beginner Error Handling
0%
01

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 try and except.
  • Handle specific exception types.
  • Handle multiple exceptions.
  • Access exception information using as.
  • Use the else block.
  • Handle errors in user input and file operations.
  • Write clear and useful error messages.
  • Avoid common exception-handling mistakes.
02

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:

Python
number = int("hello")
Output
ValueError: invalid literal for int()

If an exception is not handled, Python normally stops the current program and displays a traceback.

Exception handling gives your program a safety net.

Instead of crashing immediately, your program can respond appropriately to expected problems.

03

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.

Important idea

Exception handling is not about pretending errors do not exist. It is about handling predictable failures deliberately.

04

Basic try / except Syntax

The basic structure is:

Python
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.

The flow is:
  1. Enter the try block.
  2. Run the code.
  3. If no exception occurs, continue normally.
  4. If an exception occurs, find a matching except.
  5. Execute the matching handler.
05

Handling a Specific Exception

Good Python programs usually catch the specific exception they expect.

Python
try:
    age = int("abc")

except ValueError:
    print("Invalid age.")
Output
Invalid age.

This is better than catching every possible exception because the program clearly communicates what problem it knows how to handle.

06

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.

Python
try:
    number = int("python")
    print(number)

except ValueError:
    print("Please provide a valid integer.")
Output
Please provide a valid integer.

This pattern is extremely useful when working with user input.

07

Handling ZeroDivisionError

Python raises ZeroDivisionError when you attempt to divide a number by zero.

Python
try:
    result = 100 / 0
    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero.")
Output
Cannot divide by zero.
Do not hide the problem.

Handle the error with a meaningful response instead of silently ignoring it.

08

Multiple except Blocks

A single try block can have multiple except blocks.

Python
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.

Why this is useful

Different errors can receive different, meaningful responses.

09

Handling Multiple Exceptions Together

Sometimes different exceptions should receive the same response.

You can group exception types inside a tuple.

Python
try:
    value = int("hello")

except (ValueError, TypeError):
    print("Invalid input.")

This is useful when different exceptions have the same handling logic.

Syntax

Use parentheses around multiple exception types: (ValueError, TypeError).

10

The Exception Object with as

You can store the exception object in a variable using the as keyword.

Python
try:
    number = int("abc")

except ValueError as error:
    print("Error:", error)

The variable error contains information about the exception.

Example Output
Error: invalid literal for int() with base 10: 'abc'

Exception objects are particularly useful for debugging, logging and producing informative messages.

11

The else Block

Python allows an else block after except.

The else block runs only when the try block finishes without an exception.

Python
try:
    number = int("25")

except ValueError:
    print("Invalid number.")

else:
    print("Number:", number)
Output
Number: 25
Think of it this way:

try = attempt something, except = handle failure, else = continue after success.

12

try / except / else

These three blocks can work together to make the structure of a program clearer.

Python
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.

Best practice

Keep the try block focused on the operation that can actually raise the exception.

13

Nested try / except

A try / except block can exist inside another try block.

Python
try:
    print("Outer operation")

    try:
        number = int("abc")
        print(number)

    except ValueError:
        print("Inner error handled.")

except Exception:
    print("Outer error handled.")
Output
Outer operation
Inner error handled.
Use nesting carefully.

Deeply nested exception handling can make a program difficult to understand. Prefer a simple structure whenever possible.

14

Practical User Input Example

One of the most common uses of try / except is validating user input.

Python
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.

Real-world importance

Input validation is essential in forms, calculators, registration systems, dashboards and command-line applications.

15

File Handling with try / except

Files may not exist, may be inaccessible, or may have permission problems.

Exception handling can make file operations safer.

Python
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.

Common file exceptions
  • FileNotFoundError
  • PermissionError
  • IsADirectoryError
16

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.

Do not use exception handling to hide bugs.

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.

17

Writing Good Error Messages

An error message should help the user understand what happened and, when possible, what to do next.

Better
except ValueError:
    print("Please enter your age as a whole number.")

Compare that with:

Less Helpful
except ValueError:
    print("Error.")
Good error messages should be:
  • Clear
  • Specific
  • Relevant
  • Helpful
  • Easy for the intended user to understand
18

Common try / except Mistakes

1. Using a bare except:

This catches almost everything and can hide problems.

Avoid this when possible:
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.

19

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.

20

Mini Challenge — Safe Calculator

Build a calculator that does not crash when the user enters invalid data.

Your calculator should:
  • 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

Python
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)
Challenge extension

Improve the calculator so that it keeps asking for calculations until the user chooses to exit.

21

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?

22

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.
Specific exception types should generally be preferred.
Multiple except blocks can handle different problems.
Exception objects can be accessed using as.
else runs when the try block succeeds.
Exception handling is useful for user input, files, calculations and many real-world tasks.
Do not use exception handling to silently hide programming bugs.
Key takeaway

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.