Python Exception Handling

Handle runtime errors with try, except, else, and finally.

When writing programs, errors are sometimes unavoidable. A user might enter invalid input, a file may not exist, or a network connection could fail. If these situations are not handled properly, the program may stop running unexpectedly.

Python provides exception handling to deal with such errors gracefully. Instead of crashing, a program can catch an error, display a helpful message, and continue running or exit safely.

In this lesson, you will learn what exceptions are, why exception handling is important, and how to use try, except, else, finally, and raise to build reliable Python programs.

What is an Exception?

An exception is an error that occurs while a program is running. When Python encounters an unhandled exception, it normally stops the program and displays an error message.

python
number = 10 / 0

print(number)

Output

text
ZeroDivisionError: division by zero

Dividing by zero is not allowed, so Python raises a ZeroDivisionError.

Why Use Exception Handling?

Without exception handling, a single error can stop the entire program. With exception handling, you can:

  • Prevent the program from crashing.
  • Display user-friendly error messages.
  • Handle different types of errors separately.
  • Make programs more reliable and professional.

The try and except Blocks

The most common way to handle exceptions is with try and except statements.

Syntax

python
try:
    # Code that may cause an error
    pass
except:
    # Code to handle the error
    pass

Example

python
try:
    number = 10 / 0
    print(number)
except:
    print("An error occurred.")

Output

text
An error occurred.

Instead of stopping, the program catches the error and displays a message.

Handling Specific Exceptions

It is better to catch specific exceptions rather than using a general except block. This makes code clearer and easier to debug.

python
try:
    number = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero.")

Output

text
You cannot divide by zero.

Handling Multiple Exceptions

A single program can encounter different types of errors. Separate except blocks let you respond appropriately to each one.

python
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(result)

except ValueError:
    print("Please enter a valid number.")

except ZeroDivisionError:
    print("Division by zero is not allowed.")

This program handles invalid input and division by zero separately.

The else Block

The else block runs only when no exception occurs. It keeps successful execution separate from error handling.

python
try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input.")
else:
    print("You entered:", number)

The finally Block

The finally block always runs, whether an exception occurs or not. It is often used to release resources or perform cleanup tasks.

python
try:
    file = open("notes.txt", "r")
    print(file.read())

except FileNotFoundError:
    print("File not found.")

finally:
    print("Program finished.")

Output if the file does not exist

text
File not found.
Program finished.

Raising Exceptions

Sometimes you need to create an exception when a required condition is not met. Use the raise keyword to enforce rules and validate data.

python
age = 15

if age < 18:
    raise ValueError("Age must be at least 18.")

This stops the current execution and displays the specified error message unless another part of the program catches it.

Common Built-in Exceptions

ExceptionDescription
ValueErrorInvalid value provided
TypeErrorWrong data type used
NameErrorVariable not found
IndexErrorInvalid list index
KeyErrorDictionary key not found
FileNotFoundErrorFile does not exist
ZeroDivisionErrorDivision by zero
AttributeErrorInvalid object attribute

Knowing these exception types helps you write precise error-handling code.

Best Practices

  • Catch specific exceptions whenever possible.
  • Avoid a blank except block unless absolutely necessary.
  • Display clear and meaningful error messages.
  • Use finally for cleanup tasks such as releasing resources.
  • Do not use exception handling to hide programming mistakes; fix the root cause whenever possible.

These practices improve the quality and reliability of your programs.

Real-World Example

The following program asks the user for two numbers and performs division safely.

python
try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    result = num1 / num2

except ValueError:
    print("Please enter valid numbers.")

except ZeroDivisionError:
    print("The second number cannot be zero.")

else:
    print("Result:", result)

finally:
    print("Calculation completed.")

This example demonstrates how multiple exception-handling features work together to create a robust program.

Key Takeaways

  • An exception is an error that occurs while a program is running.
  • Exception handling prevents programs from crashing unexpectedly.
  • The try block contains code that may cause an exception.
  • The except block handles errors gracefully.
  • The else block runs only if no exception occurs.
  • The finally block always executes, making it useful for cleanup tasks.
  • Use raise to create exceptions when application rules are not met.
  • Catch specific exceptions instead of relying on a general except block.
  • Proper exception handling makes programs more reliable, user-friendly, and maintainable.
  • Exception handling is an essential skill for building professional Python applications.
Let's learn with DevBrainBox AI