Python is a multi-purpose object-oriented programming language that comes with numerous built-in exceptions such as ImportError, OSError, etc. Using Exceptions, programmers can handle mistakes and unpredicted circumstances in their code. A Python program raises an exception when an error occurs, and if the exception is not caught and handled, the program ends.
This blog post will give you a brief understanding of how to manually raise exceptions in Python.
How to Raise Exceptions in Python?
There are multiple methods of manually raising exceptions in Python. Some of them are listed below:
- Using Raise Keyword
- Using Try Except
- Using assert Statement
Let’s discuss them one by one.
Method 1: Raise Exceptions With the Help of Raise Keyword
To manually raise exceptions in Python, use a Raise keyword. Raise keyword enables the users to throw an exception with a custom/user-defined error message as mentioned below:
def divide_numbers(num1, num2):
if num2 == 0:
raise ZeroDivisionError("cannot be Divided by zero.")
return num1/num2
print(divide_numbers(3,0))
In the above code:
- A function named divide_numbers is defined which takes two arguments, num1 and num2
- If num2 is equal to 0, it will throw a ZeroDivisionError with the help of a “raise” keyword.
- The divide_numbers() function will stop executing and will return the error message.
The output of the code is attached below:
It can be seen that we have divided 3 by 0, so it raised an exception and printed the message “The denominator cannot be zero”.
Let’s see another simpler example to understand the concepts better.
num = eval(input("Enter a number: "))
if num < 15:
raise ValueError('num should not be less than 10!')
print(num)
In the above code:
- The program prompts the user to provide an input number.
- If the provided number is less than 10, the program will throw an exception. Otherwise, the program will display the number.
The output of the above code is attached below:
It can be seen that the provided number is 3 which is less than 10 so it throws a ValueError.
Method 2: Raise Exceptions With the help of Try-Except
Nowadays developers use a modern exception-handling technique known as “try-except”. The Try block checks for errors in the code and if an error is present, the Python code jumps to the except block. The except block handles and manages the exception. Let’s raise an exception using try-except as shown below:
num0 = 10
try:
num1 = input("1st number: ")
num2 = input("2nd number: ")
result = (int(num1) * int(num2))/(num0 * int(num2))
except ValueError as ve:
print(ve)
exit()
print(result)
Here,
- We have defined a variable num0 and its value is set to 10.
- The program now enters the try block and checks that if the given two numbers are integers, it displays their output.
- If the given numbers are not integers, the program enters the except block and throws a ValueError.
The output of the code is attached below:
It can be seen that the 1st number 6 which is an integer is divided by 0.5 which is a float number so an exception is thrown stating “ValueError”.
Method 3: Raise Exceptions With the Help of Assert Statement
Exceptions can also be raised in Python by utilizing the assert statement. It takes a single statement that is equal to true. If the exception is False, Python throws an AssertionError.
def split(num1, num2):
assert num2 != 0, "Cannot divide the number by zero"
return num1/num2
print(split(5,0))
In the above code:
- A function split is defined which takes 2 arguments.
- If num2 is not equal to 0, the assertion “Cannot divide the number by zero” is passed and the function moves to the next line of the code.
- If num2 is equal to zero, the assert statement fails and Python throws an ExceptionError.
- In the last line, the function is called and 5 and 0 are provided as parameters.
Conclusion
Exceptions allow programmers to handle mistakes and unpredicted conditions in their code. There are multiple methods of manually throwing exceptions in Python. The first method is by using the raise keyword, the 2nd method is by using try-except keywords and the last method is by using the assert method. All are convenient methods but the most commonly used method by developers is the try-except method.