Manually Raise or Throw Exception in Python

How to manually raise or throw an exception in Python? You may want to manually raise or throw an exception to signal that an error has occurred or to control the flow of your program. We can use the assert statement and the sys.exc_info() function to raise and re-raise exceptions. In this article, we will explore how to manually raise exceptions with examples.

Exceptions are an important concept in Python that allows you to handle errors and unexpected situations in your code. When an error occurs in a Python program, an exception is raised and the program terminates unless the exception is caught and handled using try except.

1. Quick Examples of Manually Raising or Throwing Exception

The following examples will provide you with a high-level overview of how to manually raise different types of exceptions in Python. For each example, we will define a function that accepts one or more arguments, and then use the raise statement to manually raise an exception if a certain condition is met.


# Manually raising a ValueError exception 

# Accepts an integer argument
def divide_by_three(x):
    # if the argument is divisible by three
    if x % 3 != 0:
        # If not, raise a ValueError exception 
        raise ValueError("Not divisible by three")
    # Return the result of the division
    return x / 3

# Call the function with a non-divisible 
try:
    result = divide_by_three(5)
except ValueError as e:
    print(e)

# Call the function with a divisible 
result = divide_by_three(9)
print(result)

2. Manually Raising Exceptions using raise Keyword

Exceptions are raised automatically when an error occurs during program execution. However, you can also raise exceptions manually using the raise keyword in Python. This allows you to control the flow of your program and handle errors in a more controlled manner.

To manually raise an exception in Python, you can use the raise keyword followed by the type of exception you want to raise. For example, to raise a ValueError exception, you would use raise ValueError. You can also include an optional error message that provides additional information about the exception.

See the following example:


# Manually raising a TypeError exception

def square_root(x):
    if not isinstance(x, (int, float)):
        raise TypeError("Must be an integer or float")
    if x < 0:
        raise ValueError("Argument must be non-negative")
    return x ** 0.5

try:
    result = square_root("4")
except TypeError as e:
    print(e)

try:
    result = square_root(-1)
except ValueError as e:
    print(e)

result = square_root(4)
print(result)

Yields the following output:


# Output:
Argument must be an integer or float
Argument must be non-negative
2.0
  1. The argument should be either an int or a float. Raise a TypeError exception for other types.
  2. If the argument is negative raise a ValueError exception.
  3. The function raises a TypeError exception for the argument that’s not an int or float, and a ValueError exception for the negative arguments.

3. Creating Custom Exception Classes

Python allows you to create your own custom exception classes to describe specific types of errors that may occur in your code. This provides more detailed information about the error to make it easier to debug your code.

To create a custom exception class:

  • Define a new class that inherits from the built-in Exception class.
  • Customize the attributes and methods of the new class to suit your needs.
  • Raise an instance of the custom exception class using the raise statement.

See example:


# Custom exception class
class MyCustomException(Exception):
    pass

# Raise custom exception
def my_function(arg):
    if arg < 0:
        raise MyCustomException("Argument must be non-negative")
    return arg * 2

Now use this Custom exception class to manually throw an exception:


# Handle manally custom exception
try:
    result = divide(5, 0)
except InvalidArgumentError as e:
    print("An error occurred:", e)

4. assert Statement to Raise Exceptions

You can use the assert statement to check that a condition is true, and raise an exception if it’s not. The assert statement takes a single expression that should evaluate to True. If the expression is False, Python raises an AssertionError exception with a default error message.


# Using assert statement
def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

divide(5/0)

When you use the assert statement to check conditions, it’s important to keep in mind that:

  • The assert statement is for debugging and testing purposes, and should not be used to handle user input or other kinds of input errors.
  • If the assert statement raises an exception, it means that there is a bug in your code that needs to be fixed.
  • You can disable the assert statement by running Python with the -O (optimize) option, in which case all assert statements are ignored.

5. sys.exc_info() Function – Re-raise Exceptions

You can also use the sys.exc_info() function to get information about the current exception that is being handled, and then re-raise the exception to pass it on to a higher level of the program.

  • This technique can be useful for adding additional processing, logging, or other actions.
  • Re-raising an exception can make it harder to debug problems.
  • You should use this technique only when it’s necessary to handle specific exceptions in a particular way.

import sys

def divide():
    try:
        # Some code that might raise an exception
        x=1 / 0
    except:
        # Get information about the current exception
        exc_type, exc_value, exc_traceback = sys.exc_info()
        # Do some additional processing, logging, etc.
        # ...
        # Re-raise the exception to pass it on to a higher level
        raise exc_type(exc_value).with_traceback(exc_traceback)
divide()

6. Summary and Conclusion

We have discussed the different methods of manually raising or throwing an exception in Python. You have learned that the raise keyword can be used to raise built-in exceptions, and custom exception classes can be created for more specific use cases.

We have explored the use of the assert statement and the sys.exc_info() function for raising exceptions in different scenarios. I hope this article was helpful to you. If you have any questions or feedback, please leave it in the comments below.

Happy coding!

AlixaProDev

I am an astute software engineer with extensive 3+ years of experience in developing full-stack web applications. My skillets include building backend services for different databases. Mainly I work with Python, Flask, Django, and FastAPIs. Being Python Specialist, I have worked with Numpy, Pandas, and other Python Libraries to build tools that make ETL normalization easier.

Leave a Reply