How to manually raise / throw an exception in Python?

In this Python tutorial, we will discuss how to manually raise or throw an exception.

Table Of Contents

Let’s dive into the tutorial.

Exceptions in Python

When our application fails and returns an error, then it is very difficult to locate the reason of an error in a big application. Like in applications with 1000 or more lines of code. To check and handle errors in an application, exceptions are used. An exception is a condition in an application that stops the execution of code.

We can catch exceptions using except keyword followed by the try block. All the functional code is written in the try block and code for handling the exception part is written in the except block.

Syntax:

try:
    statements
    ..........
    ..........
except Exception:
    statements
    ..........
    ..........

Example:
In this example, we will divide 45 by 0 in the try block. It should raise an exception and we will handle the exception in except block. Then we will display the exception in except block.

try:
    # Divide 45 with 0
    print(45 / 0)  
except Exception as e:
    # Handle the exception and Display the exception 
    print("Exception Occurred : ", e)

Output:

Exception Occurred :  division by zero

We can see that the “division by zero” exception message is displayed. It is because, we can’t divide any number by 0. It is also possible to manually raise this kind of exception. Let’s raise some exceptions manually.

The “raise” in python is a keyword, that is used to raise the exceptions manually. It is used inside the try block.

Syntax:

raise exception_name("Message")

Where exception_name is the error name and Message is a string that has to be returned.

Manually raise ZeroDivisionError exception using raise statement

Here, we will see how to raise the ZeroDivisionError exception with the raise keyword. This exception occurs when we divide any number with 0.

Syntax:

try:
    statements
    ..........
    raise ZeroDivisionError("message")    
except Exception as ex:
    statements
    ..........

Example:

In this example, we will create two variables a and b initialized with 45 and 0. Then we will raise an exception if b is equal to 0.

# Declare two variables
a=45
b=0

# try block
try:
    # raise ZeroDivisionError if b == 0
    if (b == 0):
        raise ZeroDivisionError("We can't divide any number by 0")
except Exception as ex:
    print("Exception occured: ",ex)

Output:

Exception occured:  We can't divide any number by 0

We can see that exception is raised with the given message.

Manually raise TypeError exception using raise statement

Here, we will see how to raise the TypeError exception with the raise keyword. This exception occurs when the datatype is mismatched.

Syntax:

try:
    statements
    ..........
    raise TypeError("message")
except Exception as ex:
    statements
    ..........

Example:

In this example, we will raise an exception when the datatype of a string – ‘thispointer’ is not equal to an integer.

try:
  # raise an error the string - "thispointer" is not the integer
  if not type("thispointer") is int:
        raise TypeError("Not an integer")

except Exception as ex:
    print("Exception occured: ", ex)

Output:

Exception occured:  Not an integer

We can see that exception is raised with the given message.

Manually raise ValueError exception using the raise statement

Here, we will see how to raise the ValueError exception with the raise keyword. This exception occurs when the value is mismatched.

Syntax:

 try:
    statements
    ..........
    raise ValueError("message")  
except Exception as ex:
    statements
    ..........

Example:

In this example, we will raise an exception when the number of days in a week is 8.

weekdays = 8

try:
    # raise an ValueError exception if 
    # total number of days in a week is 8
    if (weekdays > 7):
        raise ValueError("There are no 8 days in a week")
except Exception as ex:
    print("Exception occured: ",ex)

Output:

Exception occured:  There are no 8 days in a week

We can see that exception is raised with the given message.

Summary

We have seen what is an exception and also noticed that it is a good practice to use try-catch blocks in every part of the code. It is also possible to raise an exception/s manually using the raise keyword. In this tutorial, we discussed three types of exceptions that are manually raised. Based on the choice and use case, you can use the exceptions. Happy Coding.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top