“raise” Keyword in Python: Raising Exceptions in Your Code

"raise" Keyword in Python: Raising Exceptions in Your Code

In Python, exceptions are errors or problems that arise during the execution of code. They are the runtime errors which occur when the program encounters an unexpected situation, like an input error or an arithmetic error. The raise keyword in Python is used to generate a new exception, indicating that an error has occurred in the code. In this tutorial, we will learn how to use the raise keyword in Python to raise exceptions in your code.

What is the raise keyword in Python?

The raise keyword in Python is used to generate a new exception, indicating that an error has occurred in the code. The raise statement is used for handling exceptions explicitly in the program. It is used to create a new exception object or to raise an existing exception.

Basic Syntax of raise

The basic syntax of raise statement is as follows:

raise exception_name

The exception_name is the name of the exception to be raised. We can also provide an optional error message with the exception.

Example using raise

Let’s take an example that explains how raise works. Assume that we have a function which accepts only positive numbers as parameters. To ensure that the function receives only positive numbers as parameters, we can add a check in the function. If the parameter passed is not a positive number, then we will raise an exception explicitly using the raise keyword. Here is the code for the same:

def check_positive_num(num):
    if num <= 0:
        raise ValueError("Invalid number, please enter positive number only.")
    else:
        return num

print(check_positive_num(-5))

The code above raises a ValueError exception with the message “Invalid number, please enter positive number only.” The exception is raised in the function check_positive_num, which is called with a negative number as input. The exception is caught by the Python interpreter and an error message is displayed, as shown in the output below:

Traceback (most recent call last):
  File "test.py", line 7, in 
    print(check_positive_num(-5))
  File "test.py", line 3, in check_positive_num
    raise ValueError("Invalid number, please enter positive number only.")
ValueError: Invalid number, please enter positive number only.

How to Create an Exception in Python?

In Python, we can create our own exception classes using the Exception class. Exception is a base class provided by Python which can be inherited to create custom exceptions. To create your own exception class, you need to create a new class that derives from the Exception class, and then define your own constructor and any other methods that you need for your exception class.

Example of Creating an Exception Class

Here is an example of creating a custom exception class named CustomException:

class CustomException(Exception):
    def __init__(self, value):
        self.value = value
    
    def __str__(self):
        return repr(self.value)

In the code above, we define a new class named CustomException that inherits from the Exception base class. We also define a constructor that takes one argument, and a method that converts the exception value into a string.

Example Using Custom Exception Class with raise keyword

Now that we have defined our own exception class CustomException, let’s use it in a program. In this example, we will raise the exception explicitly using the raise keyword if the input value is less than or equal to 2. Here is the code for the same:

def check_value(num):
    if num <= 2:
        raise CustomException("Invalid input value, please enter value greater than 2.")
    else:
        return num

try:
    value = check_value(1)
    print("Value accepted:", value)
except CustomException as e:
    print("Caught an exception:", e)

In the code above, we call the function check_value() with a parameter value of 1. Since the value of the parameter passed to the function is less than or equal to 2, it raises a CustomException with the message “Invalid input value, please enter value greater than 2.” This exception is caught by the try..except block, and an error message is displayed as shown in the output below:

Caught an exception: 'Invalid input value, please enter value greater than 2.'

Conclusion

In this tutorial, we have learned how to raise exceptions using the raise keyword in Python. We have seen how to use the raise keyword along with the try..except block to handle exceptions in a program. We have also learned how to create our own exception classes using the Exception base class. By raising and catching exceptions explicitly in a program, we can handle errors and exceptions more effectively and provide better error messages to the user.

Leave a Reply

Your email address will not be published. Required fields are marked *