Python Exceptions – Handling Errors in Python

Introduction

Python provides a powerful mechanism called Exception Handling that allows developers to manage errors. Instead of crashing the application, exceptions can be caught and handled, enabling the program to continue running or display meaningful error messages.

Exception handling is one of the most important concepts in Python because it helps developers build reliable, secure, and user-friendly applications.

What are Python Exceptions?

An Exception is an error that occurs during the execution of a program.

When Python encounters an error, it creates an exception object. If the exception is not handled, the program stops execution and displays an error message.

Example:


num = 10
result = num / 0
print(result)

Output:

ZeroDivisionError: division by zero

In this example, Python raises a ZeroDivisionError because dividing a number by zero is not allowed.

Exceptions help developers identify and handle such situations effectively.

Why Are Exceptions Important?

Exception handling provides several benefits:

  • Prevents application crashes
  • Improves user experience
  • Makes programs more reliable
  • Simplifies debugging
  • Handles unexpected situations gracefully
  • Improves code maintainability

Without exception handling, even a small error could terminate the entire program.

Syntax

Python uses the try and except blocks to handle exceptions.


try:
    # Code that may generate an exception
except ExceptionType:
    # Error handling code

Example:


try:
    num = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Output:

Cannot divide by zero

How Exceptions Work

The exception handling process follows these steps:

  1. Python executes code inside the try block.
  2. If no error occurs, execution continues normally.
  3. If an exception occurs, Python stops the try block.
  4. The matching except block executes.
  5. The program continues running.

Example:


try:
    number = int("abc")
except ValueError:
    print("Invalid number")

Output:

Invalid number

Common Built-in Exceptions

Python provides many built-in exceptions.

Exception Description
ZeroDivisionError Division by zero
ValueError Invalid value
TypeError Wrong data type
IndexError Invalid list index
KeyError Missing dictionary key
NameError Undefined variable
FileNotFoundError File does not exist
AttributeError Invalid object attribute
ImportError Module import failure

Understanding these exceptions helps developers troubleshoot errors quickly.

Handling ZeroDivisionError

This exception occurs when dividing by zero.

Example:


try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed")

Output:

Division by zero is not allowed

Handling ValueError

A ValueError occurs when an invalid value is provided.

Example:


try:
    age = int("Python")
except ValueError:
    print("Please enter a valid number")

Output:

Please enter a valid number

Handling TypeError

A TypeError occurs when incompatible data types are used.

Example:


try:
    result = "10" + 5
except TypeError:
    print("Invalid operation")

Output:

Invalid operation

Handling IndexError

An IndexError occurs when accessing an invalid list position.

Example:


numbers = [10, 20, 30]
try:
    print(numbers[5])
except IndexError:
    print("Index out of range")

Output:

Index out of range

Handling KeyError

A KeyError occurs when a dictionary key is missing.

Example:


student = {
    "name": "John"
}
try:
    print(student["age"])
except KeyError:
    print("Key not found")

Output:

Key not found

Handling Multiple Exceptions

A program may generate different types of exceptions.

Example:


try:
    number = int(input("Enter number: "))
    result = 100 / number
except ValueError:
    print("Invalid input")
except ZeroDivisionError:
    print("Cannot divide by zero")

Possible Output:

Invalid input
or
Cannot divide by zero

Using a Generic Exception

You can handle all exceptions using the base Exception class.

Example:


try:
    x = 10 / 0
except Exception as e:
    print("Error:", e)

Output:

Error: division by zero

The variable e stores the exception message.

Using else Block

The else block executes only when no exception occurs.

Example:


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

Input:


25

Output:

You entered: 25

Using the finally Block

The finally block always executes, regardless of whether an exception occurs.

Example:


try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error")
finally:
    print("Program finished")

Output:

Program finished

This is useful for cleanup tasks.

Raising Exceptions

Python allows developers to create exceptions manually using raise.

Syntax


raise ExceptionType("Message")

Example:


age = -5
if age < 0:
    raise ValueError(
        "Age cannot be negative"
    )

Output:

ValueError: Age cannot be negative

Custom Exceptions

Developers can create their own exception classes.

Example:


class InvalidAgeError(Exception):
    pass
age = -10
if age < 0:
    raise InvalidAgeError(
        "Invalid age entered"
    )

Output:

InvalidAgeError:

Invalid age entered

Custom exceptions improve application-specific error handling.

Example

The following program demonstrates exception handling.


try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    result = num1 / num2
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", result)
finally:
    print("Calculation completed")

Input:


10 
2

Output:

Result: 5.0

Calculation completed

Real-life Example

Imagine you are building an ATM application.

A user may attempt to withdraw more money than available.


balance = 5000

try:
    amount = int(
        input("Enter amount: ")
    )
    if amount > balance:
        raise ValueError(
            "Insufficient balance"
        )
    balance -= amount
    print("Withdrawal successful")
except ValueError as e:
    print(e)

Input:


7000

Output:

Insufficient balance

Common Mistakes

1. Not Using Exception Handling

Incorrect:


result = 10 / 0

Output:

ZeroDivisionError

Correct:


try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error")

2. Catching Every Exception Unnecessarily

Incorrect:


except:
    print("Error")

Correct:


except ValueError:
    print("Invalid value")

Use specific exceptions whenever possible.

3. Ignoring Exception Messages

Incorrect:


except Exception:
    print("Error")

Correct:


except Exception as e:
    print(e)

This provides useful debugging information.

4. Using raise Incorrectly

Incorrect:


raise "Error"

Correct:


raise ValueError("Error")

5. Forgetting finally for Cleanup

Incorrect:


try:
    pass
except:
    pass

Better:


finally:
    print("Cleanup completed")

Best Practices

1. Use Specific Exceptions


except ValueError:

More precise and readable.

2. Keep try Blocks Small

Only place risky code inside the try block.

3. Display Helpful Messages


print("Please enter a valid number")

Improves user experience.

4. Log Errors in Large Applications

Store exception details for debugging.

5. Use finally for Resource Cleanup


finally:
    print("Closing resources")

Difference Between Exception Handling Blocks

Block Purpose
try Contains risky code
except Handles exceptions
else Executes if no exception occurs
finally Always executes
raise Creates an exception manually

Conclusion

Python Exceptions provide a powerful mechanism for handling runtime errors. Instead of allowing applications to crash unexpectedly, exception handling enables developers to detect, manage, and recover from errors effectively.

By using try, except, else, finally, and raise, developers can create reliable and user-friendly applications. Python also offers many built-in exceptions such as ValueError, TypeError, IndexError, and ZeroDivisionError, while custom exceptions allow developers to handle application-specific situations.

Related Python Tutorials