Lesson 42 of 70 – Exception Handling
60%

Python Exception Handling

An exception is an error that occurs while a Python program is running. Exception handling allows us to detect and handle these errors so that the program can respond properly instead of stopping unexpectedly.

Note: Python uses try, except, else, and finally blocks to handle exceptions.
What is an Exception?

An exception is an event that interrupts the normal flow of a program because something unexpected happened during execution.

For example:

number = 10
result = number / 0

print(result)

The program cannot divide a number by zero, so Python raises an exception.

Output:
ZeroDivisionError
Why Handle Exceptions?
  • Prevent the program from terminating unexpectedly.
  • Display meaningful error messages.
  • Handle unexpected input safely.
  • Allow the program to continue when appropriate.
  • Make applications more reliable.
  • Separate normal program logic from error-handling logic.
try and except

The try block contains code that may raise an exception. The except block handles the exception.

try:
    number = 10 / 0

except:
    print("An error occurred")
Output:
An error occurred
Handling a Specific Exception

It is generally better to catch a specific exception when you know what kind of error may occur.

try:
    number = 10 / 0

except ZeroDivisionError:
    print("Cannot divide by zero")
Output:
Cannot divide by zero
ZeroDivisionError

ZeroDivisionError occurs when a number is divided by zero.

try:
    result = 20 / 0

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

ValueError occurs when a function receives a value of the correct general type but an inappropriate value.

try:
    age = int("abc")

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

TypeError occurs when an operation is applied to an inappropriate type.

try:
    result = "10" + 5

except TypeError:
    print("Incompatible data types")
Output:
Incompatible data types
NameError

NameError occurs when Python cannot find a name that has not been defined.

try:
    print(username)

except NameError:
    print("Variable is not defined")
Output:
Variable is not defined
IndexError

IndexError occurs when you try to access a list or sequence using an index that does not exist.

numbers = [10, 20, 30]

try:
    print(numbers[5])

except IndexError:
    print("Index does not exist")
Output:
Index does not exist
KeyError

KeyError occurs when you try to access a dictionary using a key that does not exist.

student = {
    "name": "Amit",
    "age": 20
}

try:
    print(student["mobile"])

except KeyError:
    print("Key does not exist")
Output:
Key does not exist
FileNotFoundError

FileNotFoundError occurs when Python tries to open a file that does not exist at the specified location.

try:
    file = open("data.txt", "r")

except FileNotFoundError:
    print("File not found")
Output:
File not found
Multiple except Blocks

A program can have multiple except blocks to handle different types of exceptions.

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

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

except ZeroDivisionError:
    print("Cannot divide by zero")

Each exception type can have its own handling logic.

Catching Multiple Exceptions Together

Multiple exception types can be handled by one except block using a tuple.

try:
    number = int("abc")

except (ValueError, TypeError):
    print("Invalid value")
Output:
Invalid value
Getting the Exception Message

You can store the exception object using as and display its message.

try:
    result = 10 / 0

except ZeroDivisionError as error:
    print(error)
Example Output:
division by zero
The else Block

The else block runs when no exception occurs in the try block.

try:
    number = 10 / 2

except ZeroDivisionError:
    print("Cannot divide by zero")

else:
    print("Calculation successful")
Output:
Calculation successful
The finally Block

The finally block executes whether an exception occurs or not. It is commonly used for cleanup operations.

try:
    number = 10 / 2

except ZeroDivisionError:
    print("Error")

finally:
    print("Program finished")
Output:
Program finished
try, except, else and finally

Python allows all four blocks to be used together.

try:
    number = 10 / 2

except ZeroDivisionError:
    print("Error occurred")

else:
    print("No error occurred")

finally:
    print("Execution completed")
Output:
No error occurred
Execution completed
Raising an Exception

The raise statement is used when you want to explicitly raise an exception.

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")
Result:
ValueError: Age cannot be negative
Custom Error Message
marks = 120

if marks > 100:
    raise ValueError("Marks cannot be greater than 100")
Result:
ValueError: Marks cannot be greater than 100

Custom messages make errors easier to understand.

User Input Exception Handling

Exception handling is especially useful when working with user input.

try:

    age = int(input("Enter your age: "))

    print("Your age is:", age)

except ValueError:

    print("Please enter a valid number")

If the user enters text instead of a valid integer, the program handles the error without terminating at that point.

Exception Handling with Files
try:

    file = open("data.txt", "r")
    content = file.read()
    print(content)

except FileNotFoundError:

    print("The file does not exist")

finally:

    print("File operation completed")

The finally block can be used for cleanup logic. For file handling, the with open(...) pattern is usually preferred because it handles closing the file automatically.

Common Python Exceptions
Exception Meaning
ValueError Invalid value for an operation.
TypeError Invalid operation for the given data type.
ZeroDivisionError Division or modulo operation by zero.
NameError A name is not defined.
IndexError Sequence index is out of range.
KeyError Dictionary key does not exist.
FileNotFoundError Requested file does not exist.
ImportError An import cannot be completed.
Best Practices for Exception Handling
  • Catch specific exceptions whenever possible.
  • Keep the try block focused on code that may fail.
  • Use meaningful error messages.
  • Do not silently ignore important errors.
  • Use finally for cleanup operations when appropriate.
  • Use raise when invalid application state should be reported explicitly.
  • Do not use exceptions as a replacement for ordinary control flow.
Exception vs Syntax Error

A SyntaxError occurs when Python cannot understand the program's syntax before the affected code can execute normally.

if True
    print("Hello")

An exception usually occurs while executing valid Python code because an unexpected condition occurs.

number = 10
result = number / 0

Understanding this difference helps when debugging Python programs.

Key Points
  • Exceptions are errors or unexpected conditions that occur during program execution.
  • try contains code that may raise an exception.
  • except handles an exception.
  • else runs when the try block completes without an exception.
  • finally runs whether an exception occurs or not.
  • raise can explicitly raise an exception.
  • Python provides many built-in exception types.
  • Specific exceptions should generally be handled explicitly.
  • Good exception handling makes programs more reliable and user-friendly.

🧠 Quick Quiz

Question: Which block is used to handle an exception in Python?