Python Exception Handling

  • Post category:python
  • Reading time:4 mins read

What is exception handling?

Exception handling in Python is a way to manage and respond to runtime errors. When an error occurs, Python typically stops and generates an exception message. Exception handling allows you to catch these exceptions and handle them gracefully, preventing your program from crashing.

Basic structure of exception handling

The basic structure of exception handling in Python uses try, except, else, and finally blocks:

  1. try block: The code that might cause an exception is placed inside the try block.
  2. except block: This block catches the exception and executes code to handle it.
  3. else block: If no exceptions are raised, the code inside the else block is executed.
  4. finally block: This block is executed no matter what, even if an exception was raised or not. It is typically used for cleanup actions.

Let’s see a simple example.

try:
    # Code that might cause an exception
    result = 100 / 0
except ZeroDivisionError as e:
    # Code to handle the exception
    print("Cannot divide by 0. Exception message: ", e)
else:
    # Code to execute if no exception occurs
    print("The result is:", result)
finally:
    # Code to execute no matter what
    print("Execution completed.")

#Output
Cannot divide by 0. Exception message:  division by zero
Execution completed.

Handling multiple exceptions

You can have multiple except blocks to handle different kinds of exceptions:

try:
    count = "Prakash Chauhan"
    result = int(count)
except (ValueError, ZeroDivisionError) as e:
    # Code to handle ValueError and ZeroDivisionError.
    print("Exception Occurred: ", e)
except Exception as e:
    # Code to handle any other exceptions.
    print("An unexpected error occurred:", e)
else:
    # Code to execute if no exception occurs
    print("The result is:", result)
finally:
    # Code to execute no matter what
    print("Execution completed.")

# Output
Exception Occurred:  invalid literal for int() with base 10: 'Prakash Chauhan'
Execution completed.

How to create custom exception in python?

You can define your own custom exceptions by creating a new class that inherits from the built-in Exception class. This allows you to create exceptions that are specific to your application’s needs and can provide more meaningful error messages or handle specific error conditions in a customized way.

Here’s a basic example of how to create and use a custom exception:

class CalculationError(Exception):
    """Custom exception class for specific error conditions."""

    def __init__(self, message, *value):
        super().__init__(message)
        self.message = message
        self.value = value


def divide(x, y):
    if x < 0:
        raise CalculationError("Negative no. not allowed.", x,y)
    elif y == 0:
        raise CalculationError("Can not divide by 0", x,y)
    else:
        return x / y


try:
    x = int(input("Enter Numerator..."))
    y = int(input("Enter Denominator..."))
    print("Output: ",divide(x, y))
except CalculationError as e:
    print(f"Input Error: {e.message}, Input Value: {e.value}")
finally:
    print("Finally block.")


# Output : Success Scenario.
Enter Numerator...100
Enter Denominator...2
Output:  50.0
Finally block.

# Output : Taking numerator as -1.
Enter Numerator...-1
Enter Denominator...100
Input Error: Negative no. not allowed., Input Value: (-1, 100)
Finally block.

# Output : Taking denominator as -1.
Enter Numerator...100
Enter Denominator...0
Input Error: Can not divide by 0, Input Value: (100, 0)
Finally block.