Table of contents
1.
Introduction
2.
Python Raise Keyword
3.
Python Raise Syntax
3.1.
Python
4.
Checking Whether an Integer is Odd or Even:
4.1.
Python
5.
Checking Error Type
5.1.
Python
6.
Raising an Exception Without Specifying Exception Class
6.1.
Python
7.
Example
7.1.
Python
8.
Advantages of the raise Keyword
9.
Frequently Asked Questions
9.1.
Can you raise multiple exceptions in a single try block?
9.2.
Is it necessary to provide an error message when raising an exception?
9.3.
Can you create custom exception classes in Python?
10.
Conclusion
Last Updated: Jul 31, 2024
Easy

Python Raise an Exception

Author Rinki Deka
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python, the raise keyword is used to manually raise exceptions. It allows you to create custom error messages & handle specific situations in your code. With the help of the raise keyword, you can stop the normal execution of a program & provide information about what went wrong. 

Python Raise an Exception

In this article, we'll explain the syntax of the raise keyword and how to check for specific error types with examples of raising exceptions in Python.

Python Raise Keyword

The raise keyword in Python is used to raise an exception manually. When you use the raise keyword, you are essentially telling Python that something has gone wrong in your code & you want to stop the normal execution. You can raise built-in exceptions like ValueError, TypeError, or RuntimeError, or you can define your own custom exceptions.

Here's a simple example of how to use the raise keyword:

x = -1
if x < 0:
    raise Exception("x should be positive")


In this code, we check if the variable x is less than 0. If it is, we raise an Exception with a custom error message saying "x should be positive". When this exception is raised, the program will stop executing & display the error message.

Python Raise Syntax

The basic syntax for using the raise keyword in Python is as follows:

raise ExceptionClass("error message")


Here, ExceptionClass is the name of the exception you want to raise. It can be a built-in exception like ValueError, TypeError, or RuntimeError, or it can be a custom exception that you define yourself. The "error message" is an optional string that provides additional information about the exception.


For example : 

  • Python

Python

def calculate_square_root(num):
if num < 0:
raise ValueError("Cannot calculate square root of a negative number")
else:
return num ** 0.5

try:
result = calculate_square_root(-4)
print(result)
except ValueError as e:
print(str(e))
You can also try this code with Online Python Compiler
Run Code


Output

Cannot calculate square root of a negative number


In this code, we define a function called calculate_square_root that takes a number as input. If the number is negative, we raise a ValueError with a custom error message. If the number is non-negative, we calculate & return its square root.

We then use a try-except block to call the calculate_square_root function with a negative number (-4). Since the function raises a ValueError for negative inputs, the exception is caught in the except block, & the error message is printed.

Checking Whether an Integer is Odd or Even:

Let's look at an example of using the raise keyword to check whether an integer is odd or even. We'll define a function that takes an integer as input & raises an exception if the integer is odd.

  • Python

Python

def check_even(num):
if num % 2 != 0:
raise Exception("The number is odd")
else:
print("The number is even")

try:
check_even(5)
check_even(10)
except Exception as e:
print(str(e))
You can also try this code with Online Python Compiler
Run Code


Output

The number is odd


In this code, we define a function called check_even that takes an integer num as input. Inside the function, we use the modulo operator % to check if num is divisible by 2. If num is not divisible by 2 (i.e., it's odd), we raise an Exception with the message "The number is odd". If num is divisible by 2 (i.e., it's even), we print "The number is even".

We then use a try-except block to call the check_even function with two different inputs: 5 & 10. When check_even(5) is called, it raises an exception because 5 is an odd number. The exception is caught in the except block, & the error message is printed. When check_even(10) is called, it prints "The number is even" because 10 is an even number.

Checking Error Type

When you raise an exception using the raise keyword, you can specify the type of exception you want to raise. This allows you to handle different types of errors differently in your code.

For example : 

  • Python

Python

def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
elif not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both arguments must be numbers")
else:
return a / b

try:
result1 = divide_numbers(10, 2)
print(result1)

result2 = divide_numbers(10, 0)
print(result2)

result3 = divide_numbers("10", 2)
print(result3)
except ZeroDivisionError as e:
print("ZeroDivisionError:", str(e))
except TypeError as e:
print("TypeError:", str(e))
You can also try this code with Online Python Compiler
Run Code


Output

ERROR!
5.0
ZeroDivisionError: Cannot divide by zero


In this code, we define a function called divide_numbers that takes two arguments a & b. Inside the function, we check for two types of errors:

1. If b is equal to 0, we raise a ZeroDivisionError with the message "Cannot divide by zero".
 

2. If either a or b is not an instance of int or float (i.e., not a number), we raise a TypeError with the message "Both arguments must be numbers".


If none of the error conditions are met, we proceed to divide a by b & return the result.

We then use a try-except block to call the divide_numbers function with different inputs. We have multiple except blocks to catch different types of exceptions:
 

- If a ZeroDivisionError occurs (when trying to divide by zero), it is caught in the first except block, & the error message is printed.
 

- If a TypeError occurs (when passing non-numeric arguments), it is caught in the second except block, & the error message is printed.

Raising an Exception Without Specifying Exception Class

In Python, you can also raise an exception without specifying the exception class. In such cases, the default Exception class is used.


For example : 

  • Python

Python

def calculate_square_root(num):
if num < 0:
raise "Cannot calculate square root of a negative number"
else:
return num ** 0.5

try:
result = calculate_square_root(-4)
print(result)
except Exception as e:
print(str(e))
You can also try this code with Online Python Compiler
Run Code


Output

exceptions must derive from BaseException


In this code, we define a function called calculate_square_root that takes a number num as input. If num is negative, we raise an exception using the raise keyword followed by a string message "Cannot calculate square root of a negative number". Note that we don't specify any exception class here.

We then use a try-except block to call the calculate_square_root function with a negative number (-4). Since the function raises an exception for negative inputs, the exception is caught in the except block, & the error message is printed.

When you raise an exception without specifying an exception class, Python automatically uses the default Exception class. However, it's generally recommended to use specific exception classes whenever possible to provide more meaningful & precise error handling in your code.

Example

Let's look at an example that shows different aspects of raising exceptions in Python:

  • Python

Python

def process_data(data):
if not isinstance(data, dict):
raise TypeError("Data must be a dictionary")

if "name" not in data:
raise KeyError("Data must contain a 'name' key")

if not isinstance(data["name"], str):
raise ValueError("Name must be a string")

if "age" not in data:
raise KeyError("Data must contain an 'age' key")

if not isinstance(data["age"], int) or data["age"] < 0:
raise ValueError("Age must be a non-negative integer")

print("Name:", data["name"])
print("Age:", data["age"])

try:
data1 = {"name": "Rahul", "age": 25}
process_data(data1)

data2 = {"name": "Sinki", "age": -5}
process_data(data2)

data3 = {"name": 123, "age": 30}
process_data(data3)

data4 = ["name", "Mehak", "age", 40]
process_data(data4)
except TypeError as e:
print("TypeError:", str(e))
except KeyError as e:
print("KeyError:", str(e))
except ValueError as e:
print("ValueError:", str(e))
You can also try this code with Online Python Compiler
Run Code


Output

ERROR!
Name: Rahul
Age: 25
ValueError: Age must be a non-negative integer


In this example, we define a function called process_data that takes a dictionary data as input. The function performs several checks on the data & raises appropriate exceptions if the conditions are not met:

1. If data is not a dictionary, a TypeError is raised with the message "Data must be a dictionary".
 

2. If the "name" key is missing in data, a KeyError is raised with the message "Data must contain a 'name' key".
 

3. If the value of the "name" key is not a string, a ValueError is raised with the message "Name must be a string".
 

4. If the "age" key is missing in data, a KeyError is raised with the message "Data must contain an 'age' key".
 

5. If the value of the "age" key is not a non-negative integer, a ValueError is raised with the message "Age must be a non-negative integer".


If all the conditions are satisfied, the function prints the name & age from the data dictionary.
 

We then use a try-except block to call the process_data function with different input dictionaries. The except blocks catch specific exceptions that may be raised by the function:

- If a TypeError occurs, it is caught in the first except block, & the error message is printed.
 

- If a KeyError occurs, it is caught in the second except block, & the error message is printed.
 

- If a ValueError occurs, it is caught in the third except block, & the error message is printed.
 

This example shows how you can use the raise keyword to enforce specific conditions & handle different types of exceptions in your code.

Advantages of the raise Keyword


1. Error Specificity: By raising specific exceptions, you can provide more meaningful & precise error messages. This helps in identifying & debugging issues in your code more effectively. For example, raising a ValueError with the message "Age must be a non-negative integer" clearly indicates the problem when an invalid age value is provided.


2. Code Readability: Raising exceptions at appropriate places in your code enhances its readability. It makes it clear to other developers (or yourself in the future) about the expected behavior & potential error conditions. When someone reads your code, they can quickly understand the assumptions & constraints you've placed on the input data.


3. Modularity & Reusability: By using the raise keyword, you can separate the error handling logic from the main code logic. This promotes modularity & reusability of your code. You can define functions or classes that raise exceptions, & the calling code can handle those exceptions separately. This allows for cleaner & more maintainable code structure.


4. Graceful Error Handling: Raising exceptions allows you to gracefully handle errors in your code. Instead of abruptly terminating the program or producing unexpected results, you can catch the exceptions using try-except blocks & take appropriate actions. This can include logging the error, displaying user-friendly messages, or performing alternative operations.


5. Debugging & Testing: Raising exceptions helps in debugging & testing your code. When an exception is raised, it provides a traceback that shows the line of code where the exception occurred & the call stack leading to that point. This information is valuable for identifying & fixing bugs. Additionally, you can write test cases that check if your code raises the expected exceptions under certain conditions.


6. Following Best Practices: Raising exceptions is considered a best practice in Python programming. It aligns with the "easier to ask for forgiveness than permission" (EAFP) principle, which suggests that it's better to attempt an operation & handle exceptions if they occur, rather than checking for conditions beforehand. By using the raise keyword, you follow this principle & write more idiomatic Python code.

Frequently Asked Questions

Can you raise multiple exceptions in a single try block?

Yes, you can raise multiple exceptions in a single try block. The exception that occurs first will be raised & caught by the corresponding except block.

Is it necessary to provide an error message when raising an exception?

No, it's not mandatory to provide an error message when raising an exception. However, it's considered good practice to include a meaningful error message to help with debugging & understanding the issue.

Can you create custom exception classes in Python?

Yes, you can create custom exception classes in Python by defining a new class that inherits from the built-in Exception class or any of its subclasses. This allows you to define specific exception types tailored to your application's needs.

Conclusion

In this article, we discussed the raise keyword in Python & its use for raising exceptions. We learned about the syntax of the raise keyword, how to check for specific error types, & how to raise exceptions with & without specifying exception classes. We also looked at a proper example that showed the different aspects of raising exceptions.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass