Exceptions in Python

Exceptions in Python

In Python, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When an exception is raised, the program can handle it using an appropriate exception-handling code, allowing the program to continue without crashing. This section covers the basics of exceptions in Python and how to handle them effectively.

1. Exception Hierarchy

Python has a built-in hierarchy of exceptions, with a base class called BaseException and a variety of specific exception classes that inherit from it. Common exception types include:

  • SyntaxError: Raised when there is a syntax error in the code.
  • IndentationError: Raised when there is an indentation error in the code.
  • NameError: Raised when a local or global name is not found.
  • TypeError: Raised when an operation is performed on an object of inappropriate type.
  • ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
  • ZeroDivisionError: Raised when dividing a number by zero.
  • FileNotFoundError: Raised when an attempt to open a non-existent file is made.
  • Exception: The base class for most built-in exceptions.

2. Handling Exceptions

To handle exceptions in Python, you can use the try...except block. Here's the basic structure:

try:
    # Code that may raise an exception
except ExceptionType:
    # Handle the exception here

For example, if you want to catch a ValueError:

try:
    number = int("abc")
except ValueError:
    print("A ValueError occurred. Please enter a valid number.")

You can also catch multiple exception types in a single except block:

try:
    # Code that may raise an exception
except (ExceptionType1, ExceptionType2):
    # Handle the exception here

3. Handling Multiple Exceptions

To handle multiple exceptions with different handling code, you can use multiple except blocks:

try:
    # Code that may raise an exception
except ExceptionType1:
    # Handle ExceptionType1
except ExceptionType2:
    # Handle ExceptionType2

4. The else and finally Blocks

You can include else and finally blocks in your try...except structure:

  • The else block is executed if no exception is raised in the try block.
  • The finally block is always executed, whether an exception is raised or not.
try:
    # Code that may raise an exception
except ExceptionType:
    # Handle the exception here
else:
    # Code to execute if no exception is raised
finally:
    # Code to execute always

5. Raising Exceptions

You can raise exceptions explicitly using the raise statement. This can be useful in your code to signal specific error conditions.

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b

6. Exception Objects

When an exception is raised, Python creates an exception object containing information about the exception. You can access this information by using as in the except block.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Exception: {e}")

Understanding how to handle exceptions in Python is crucial for writing robust and reliable code. Proper error handling allows your program to gracefully respond to errors and prevent crashes.