
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Manually Throw or Raise an Exception in Python
While executing the program, if any statement results in an abnormal value (based on the inputs) where the interpreter doesn't know how to behave. Python throws an exception.
In Python, we can also throw or raise an exception manually using the raise keyword. This is helpful when you want to stop the program at a certain point and show that an error has occurred.
Using raise to throw a built-in exception
You can raise built-in exceptions like ValueError, TypeError, or RuntimeError using the raise statement followed by the exception name and an optional message to explain what went wrong.
Example: Raise a ValueError manually
In this example, we are raising a ValueError manually if a condition is not met -
age = -1 if age < 0: raise ValueError("Age cannot be negative.")
We get the following output -
Traceback (most recent call last): ... ValueError: Age cannot be negative.
Raising a custom exception
Python also allows you to define your own custom exception classes by extending the built-in Exception class. You can then raise these custom exceptions using the raise keyword.
Example: Raise a custom exception
In the following example, we define a custom exception and raise it if the balance is too low -
class LowBalanceError(Exception): pass balance = 100 if balance < 200: raise LowBalanceError("Balance is below the required minimum.")
We get the following output -
Traceback (most recent call last): ... LowBalanceError: Balance is below the required minimum.
Raising exceptions inside functions
You can use the raise keyword inside functions to show that an error occurred in the its logic. Then, the part of the program that called the function can catch and handle the error using a try-except block.
Example: Raising an exception from a function
In this example, we raise an exception from inside a function to show that something went wrong, and then we catch it using a try-except block -
def divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero.") return a / b try: result = divide(10, 0) except ZeroDivisionError as e: print("Caught error:", e)
We get the following output -
Caught error: Cannot divide by zero.
Reraising an exception
Sometimes, you might want to handle part of an error (i.e., handling the error partially) but still let it be handled by another part of your program later. In this case, you can use the raise keyword by itself to re-raise the current exception and pass it up for further handling.
Example: Re-raising an exception
In this example, we catch an exception and raise it again after logging a message -
try: raise ValueError("Invalid input!") except ValueError as e: print("Logging error:", e) raise
We get the following output -
Logging error: Invalid input! Traceback (most recent call last): ... ValueError: Invalid input!
Raising exceptions conditionally
You can also use the raise keyword as part of input validation or condition checks to ensure the program behaves as expected.
Example: Raise an exception on invalid input
In this example, we check if a user's input is a digit before converting it, and raise an error if it is not -
user_input = "abc" if not user_input.isdigit(): raise ValueError("Expected a number.")
We get the following output -
Traceback (most recent call last): ... ValueError: Expected a number.