Raising and Handling Custom Exceptions

Tutorial 3 of 5

Raising and Handling Custom Exceptions in Python

1. Introduction

In this tutorial, we'll cover how to raise and handle custom exceptions in Python. Exceptions are events that can modify the flow of control through a program. Python provides a number of built-in exceptions, but sometimes you may need to create and raise your own exceptions. These are known as custom exceptions.

By the end of this tutorial, you will learn:
- What are exceptions and why they are useful.
- How to raise and handle built-in exceptions.
- How to define, raise, and handle your own custom exceptions.

Prerequisites: Basic knowledge of Python Programming is required. Familiarity with Python syntax and functions would be beneficial.

2. Step-by-Step Guide

What are Exceptions?

Exceptions are events that occur during the execution of programs that disrupt the normal flow of the program's instructions.

Raising Exceptions

In Python, exceptions are triggered automatically on errors, or they can be triggered and intercepted by your code. They are handled with try-except statement. The try block is used to enclose the code that might cause an exception and the except block is used to catch and handle the exception.

try:
  # code that may raise an exception
except ExceptionType:
  # code to handle the exception

Custom Exceptions

Python allows us to create our own exceptions by deriving classes from the standard built-in exceptions. Here is a simple example:

class CustomError(Exception):
  pass

Here, we have created a new exception class named CustomError. This exception can be raised using the raise statement.

raise CustomError("This is a custom exception")

3. Code Examples

Example 1: Raising a Custom Exception

class CustomError(Exception):
  """A custom exception"""
  pass

try:
  print("Before raising exception")
  raise CustomError("This is a custom exception")
except CustomError as ce:
  print("Caught an exception:", ce)

In the above code, we first define a custom exception class CustomError. Then in a try block, we raise our custom exception using the raise statement. In the except block, we catch and handle the exception.

Example 2: Custom Exception with Additional Attributes

class ValidationError(Exception):
  """An exception for validation errors"""
  def __init__(self, message, errors):
    super().__init__(message)
    self.errors = errors

try:
  raise ValidationError("Invalid data", {"field": "value"})
except ValidationError as ve:
  print("Validation Error:", ve)
  print("Errors:", ve.errors)

In this example, we define a ValidationError class with an extra errors attribute to hold additional data about the errors.

4. Summary

In this tutorial, we've learned:
- What exceptions are and how to raise and handle them.
- How to define, raise, and handle custom exceptions.
- The importance of proper error handling in making our code robust.

For further practice, consider extending the examples given above, or creating your own scenarios where you might use custom exceptions.

5. Practice Exercises

Exercise 1:

Define a custom exception class OutOfRangeError. Write a function validate_range that takes a number as input and raises OutOfRangeError if the number is not between 1 and 10.

Exercise 2:

Extend the OutOfRangeError class from Exercise 1 to have an additional attribute value that holds the invalid number.

Solutions will be provided in the next tutorial. Practice and explore more! Happy coding!