The “Exceptions” is a critical error that arises when the program is not executed properly. It terminates the execution by displaying an “Exception” error message on the console. However, sometimes, users manually define exceptions within the program to tackle the invalid transition state or to get out of unbound looping or other program-specific errors. In such scenarios, Python gives flexibility to construct the user-defined exception using the class directly or indirectly.
This article will elaborate on the idea of manually raising exceptions in Python. However, the following topics will covered in this context:
- How to Manually Raise Exceptions in Python?
- Exceptions Handling in Python Using the “try-except” Statement
- Manually Raise the “ZeroDivisionError” With the Customize Error Message
- Manually Raise the Customize Error Message Using the “class”
- Manually Raise the “Assert” Keyword With the Customize Error Message
How to Manually Raise Exceptions in Python?
To manually raise exceptions in Python, either define a class using the “class” keyword or “try-except”. For a demonstration of how to raise the manual exception in Python, go through the below-listed approaches:
Exceptions Handling in Python Using the “try-except” Statement
The “Exception” handling in Python is raised manually within a program whenever the program encounters an undesired situation. However, in such a scenario to manually control the program, the “Exception” is raised using the “raise” keyword. However, there is a different built-in error that is raised when meeting the particular program’s wrong validation scenarios. The built-in exceptions are raised manually by customizing the error message.
Following are the built-in exceptions that are raised manually with a custom error message for the specific program operation:
Manually Raise the “ValueError” With the Customize Error Message
To check the computationally non-validating scenario, the “Valueerror” is utilized. To raise the “ValueError”, use the try-except approach. Within the “try” statement provide the condition within the “if” statement code block. And when the critical situation occurs the except statement is raised with the “exception” error. To raise the “ValueError” provide the customized error message within its braces “( )” print.
To save the “ValueError” error message the “invalid” variable is created, whenever the exception is raised, it prints the “Raised Error:” followed by the customized message. Here’s how you can raise the customized “ValueError” in Python:
# Raising a ValueError
raise ValueError("Invalid value")
# Define a function that divides two numbers
def divi(num, denum):
try:
# If the denominator is zero, raise a ZeroDivisionError
if denum == 0:
raise ValueError("invalid operation, the denominator can't be zero")
except Exception as invalid:
print("Exception Raised: ",invalid)
divi(5,0)
Output
Manually Raise the “TypeError” With the Customize Error Message
To raise the “TypeError”, save the exception in a variable “string”. Whenever the program terminates the script in the try block, the program executes the “except” block and raises the “TypeError” customized message on the kernel console.
Here’s how the “TypeError” is raised within the program manually:
raise TypeError("Invalid type")
try:
# raise an typeerror "hellousers" is not the integer
if not type("hellousers") is int:
raise TypeError("Not an integer type, its a string")
except Exception as string:
print("Exception raised: ", string)
Output
Manually Raise the “FileNotFoundError” With the Customize Error Message
The built-in “FileNotFoundError” is raised in the program, when the program terminates on not finding the specified file. The try block will execute the program until and unless the statement is “true”. If the statement is “false” the program enters into the “except” block and executes the error statement in the excerpt block.
Here’s how you can check whether the provided file is present in the directory or not:
#file path
c_path = r"C:\Users\CYBER WORLD\Desktop\newfolder\ilflogo_1.jpg"
try:
file = open(c_path)
except:
print("file not exists in the directory")
Output
Manually Raise the “FileExistsError” With the Customize Error Message
To check whether the file exists in the directory or not, you can raise the “FileExistsError” to check the program functionality. However, to interact with the operating system, you need to “import” the “os” module into the Python script. The “try” code block will execute if the file is already present in the system directory. However, if the file does not exist in the path, the “except” block executes and prints the output on the kernel console by terminating the program.
Here’s how you can manually raise the “FileExistsError” exceptions in Python:
import os
# file current directory
c_path = r"C:\Users\CYBER WORLD\Desktop\ilf_logo1.jpg"
# rename file in the same directory
n_path = r"C:\Users\CYBER WORLD\Desktop\ilf.jpg"
# try-except
try:
os.replace(c_path, n_path)
except FileExistsError:
print("Dublicate file")
print("...")
print("Removing existing file")
print("...")
# forcefully rename
os.remove(n_path)
os.rename(c_path, n_path)
print('Done removing and renaming a file')
Manually Raise the “ZeroDivisionError” With the Customize Error Message
The “ZeroDivisionError” error arises in the program when the operation is performed on two numbers and the denominator is equal to zero which is computationally not possible to solve. So the interpreter raised the error by default:
ZeroDivisionError: division by zero
However to manually raise the “ZeroDivisionError” and print the error message instead of printing the default message implement the below example program:
# Define a function that divides two numbers
def divi(num, denum):
# If the denominator is zero, raise a ZeroDivisionError
if denum == 0:
raise ZeroDivisionError("invalid operation, the denominator can't be zero")
# Otherwise, return the result of the division
return num / denum
divi(5,0)
Output
Manually Raise the Customize Error Message Using the “class”
Python gives flexible access to raising the customized key error according to the program’s need. As discussed above the inbuilt ZeroDivisionError that raised when computing the two numbers and if any divisor is divided by 0, the program will interpret the code and raise the ZeroDivisionError when the condition is not satisfied.
However, like “ZeroDivisionError” you can create and raise the customized exception depending on the program’s need. To manually raise custom exceptions in Python utilize the class object constructor. However, prevents the interpreter from raising any error in a scenario of the empty code in the program:
class unEqualLength(Exception):
pass
raise unEqualLength("List of unequal length so can't be computed.")
Output
Manually Raise the “Assert” Keyword with the Customize Error Message
Another prevalent way to manually raise the exception error is by utilizing the built-in keyword “assert”. To implement it, use the “for…in” structure to check for the condition, if the condition is “true” the iteration iterates and completes the loop. However, if the condition “False” the “assert” message prints the user-defined custom message on the kernel console. For demonstration, follow the below example code:
# consider a temperature record
temp = [ 30, 27, 26, 29, 32, 35]
# using assert to check for temperature less than or equal to average record temp
for i in temp:
assert i <= 30, "\n increase in temperature recorded"
print (str(i) + " normal temperature" )
In the above example, if the temperature is greater than 30, the “assert” condition becomes “True” and raises an “AssertionError” with the manually raised custom error. Otherwise, the program executes and returns the output on the kernel console.
To learn more about the case scenarios and the use of the “assert” keyword in Python, go through our linked article, “Use of Assert in Python”.
Output
That is all about manually raising exceptions in Python.
Conclusion
To manually raise exceptions in Python, use the “raise” keyword followed by the corresponding built-in exceptions that you want to raise for the particular operation. However, this is the direct approach to manually control the program execution if it does meet the desired scenarios. If you want to raise a manual exception utilize the “class” to construct the user-defined exception depending on the particular application. This article has demonstrated prevalent approaches and case scenarios to manually raise exceptions in Python.