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.
Frequently Asked Questions
How to manually raise exceptions in Python using the Raise keyword?
To raise exceptions in Python using the Raise keyword, you can define a custom error message and use the ZeroDivisionError as an example to handle specific error conditions.
What is the purpose of using Try Except for manually raising exceptions in Python?
In Python, using Try Except allows programmers to catch and handle exceptions in a structured way, preventing the program from crashing when errors occur during execution.
How can the assert statement be utilized for manually raising exceptions in Python?
The assert statement in Python can be used to raise exceptions based on specific conditions being met or not met, providing a straightforward and concise way to handle errors in the code.
How does Python handle exceptions when errors occur in a program?
Python raises exceptions when errors occur, and if these exceptions are not caught and handled properly, the program will terminate abruptly.
What are some common built-in exceptions in Python that programmers can utilize?
Python comes with a variety of built-in exceptions such as ImportError, OSError, and ZeroDivisionError, which programmers can use to handle errors and unexpected situations in their code.
Why is it important for programmers to manually raise exceptions in Python?
Manually raising exceptions in Python allows programmers to control error handling and improve code robustness by defining specific actions to take when certain conditions are met.
Can you provide an example of how to raise a custom exception in Python?
By using the 'raise' keyword followed by the desired exception type and a custom error message, programmers can create custom exceptions tailored to their specific needs.
How can programmers ensure proper error handling in Python programs?
Programmers can ensure proper error handling in Python programs by implementing try-except blocks, assert statements, and raising custom exceptions when necessary to gracefully manage errors and prevent program crashes.