How to Raise Exception in Python

The raise statement in Python is used to raise an exception. Try-except blocks can be used to manage exceptions, which are errors that happen while a programme is running. When an exception is triggered, the programme goes to the closest exception handler, interrupting the regular flow of execution.

  • The raise keyword is typically used inside a function or method, and is used to indicate an error condition.
  • We can throw an exception and immediately halt the running of your programme by using the raise keyword.
  • Python looks for the closest exception handler, which is often defined using a try-except block, when an exception is triggered.
  • If an exception handler is discovered, its code is performed, and the try-except block's starting point is reached again.
  • If an exception handler cannot be located, the software crashes and an error message appears.
  • Python Example for Raise an Exception

For instance, consider an example that illustrates the procedure for raising an exception in Python.

Example

# Python program to raise an exception

# divide function

def divide(a, b):

    if b == 0:

        raise Exception(" Cannot divide by zero. ")

    return a / b

try:

    result = divide(10, 0)

except Exception as e:

    print(" An error occurred: ", e)

Output:

Output

An error occurred: Cannot divide by zero.

Explanation:

In this example, the division function takes two parameters, a and b. If the value of b is zero, an exception is triggered. The try block is responsible for capturing this exception, while the unless block is used to display the appropriate error message.

Python Example to Validate Age Using Exceptions

Let’s consider an example that illustrates the process of validating age through the use of exceptions in Python.

Example

# Python program to raise an exception

# check_age function checks the age

def check_age(age):

    if age < 18:

        raise Exception(" Age must be 18 or above. ")

    else:

        print(" Age is valid. ")

try:

    check_age(17)

except Exception as e:

    print(" An error occurred: ", e)

Output:

Output

An error occurred: Age must be 18 or above.

Explanation:

In this example, the check age function takes an input value representing age and raises an exception if the age is below 18. The try block is designed to catch this exception, while the unless block outputs the corresponding error message. This serves as an illustration of how to both raise and manage exceptions in Python.

Handling Multiple Exceptions in Python

You have the ability to raise different kinds of exceptions, including but not limited to ValueError, TypeError, KeyError, and others, to signify particular errors within your code.

Example of Handling Multiple Exceptions in Python

To illustrate the process of managing multiple exceptions in Python, let's consider an example.

Example

# Python program for Handling raising exceptions

try:

    # code that might raise an exception

    value = int("a")

except ValueError:

    # code that handles the ValueError exception

    print(" Invalid value ")

except TypeError:

    # code that handles the TypeError exception

    print(" Invalid type ")

Output:

Output

Invalid Value

Explanation:

In this scenario, we are trying to convert the string "a" into an integer, which leads to a ValueError. The initial except block identifies this exception and generates a message indicating that the provided value is invalid. Should another type of exception occur, it would be addressed by the subsequent except block.

Use of finally Block in Exception Handling

The finally block can likewise be utilized to execute code that must be run regardless of whether an exception was raised. For example:

Python Example of finally Block in Exception Handling

Let us consider an example demonstrating the utilization of the finally block in exception management within Python.

Example

try:

    # code that might raise an exception

    result = 10 / 0

except ZeroDivisionError:

    # code that handles the exception

    print(" Cannot divide by zero. ")

finally:

    # code that must be executed regardless of whether an exception was raised or not

    print(" The finally block is always executed. ")

Output:

Output

Cannot divide by zero.

The finally block is always executed.

Input Required

This code uses input(). Please provide values below: