Raising an Exception to Another Exception in Python


Raising a special case to another exemption in Python includes the method of capturing and handling an original special case, and after that raising a new exception that includes an extra setting to the initial one. This procedure permits designers to adjust or wrap special cases, giving way better blunder dealing with and more enlightening mistake messages. By combining distinctive exemptions, making compound exemptions, or utilizing the 'from' keyword, software engineers can improve the strength and unwavering quality of their code by precisely passing on the nature of uncommon circumstances. Understanding these approaches empowers engineers to viably handle and oversee mistakes in their Python programs.

Approach 1: Raising an Exception within an Exception Block

The first approach includes raising an exemption inside an existing exemption square. This strategy allows you to capture the initial special case and wrap it with a modern one. Here's the algorithmic representation of the steps involved −

Algorithm

  • Step 1 − Encase the code that will raise a special case inside a try-except square.

  • Step 2 − In the except block, capture the first special case utilizing the suitable exemption course.

  • Step 3 − Pass the first special case as a contention to the variable named new_exception.

  • Step 4 − Raise the modern special case utilizing the 'raise' keyword.

Example

class CustomException(Exception):
   def __str__(self):
      return "This is a custom exception."

try:
   # Code that may raise an exception
   raise ValueError("An error occurred.")
except ValueError as original_exception:
   new_exception = CustomException(str(original_exception))
   raise new_exception

Output

Traceback (most recent call last):
  File "/home/cg/root/11237/main.py", line 8, in <module>
   raise ValueError("An error occurred.")
ValueError: An error occurred.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/11237/main.py", line 11, in <module>
   raise new_exception
__main__.CustomException: This is a custom exception

Approach 2: Raising an Exception by Creating a Compound Exception

The second approach includes making a compound special case by combining different exemptions into a single exemption. This procedure is valuable after you need to raise a single exemption that typifies numerous uncommon scenarios. Here are the steps −

Algorithm

  • Step 1 − Define multiple special case classes that speak to the diverse extraordinary scenarios.

  • Step 2 − Create a class named CompundException() that acquires from the base Special case class or any other appropriate exemption class.

  • Step 3 − Raise an exception of the unused exemption class, passing the suitable exception if the file is not found and in the except block, raise an exception to another exception which is Compound Exception.

Example

class FileNotFoundError(Exception):
   pass

class PermissionDeniedError(Exception):
   pass

class CompoundException(Exception):
   def __init__(self, file_error, permission_error):
      self.file_error = file_error
      self.permission_error = permission_error

try:
   raise FileNotFoundError("File not found.")
except FileNotFoundError as file_error:
   try:
      raise PermissionDeniedError("Permission denied.")
   except PermissionDeniedError as permission_error:
      raise CompoundException(file_error, permission_error)

Output

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 13, in <module>
   raise FileNotFoundError("File not found.")
__main__.FileNotFoundError: File not found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 16, in <module>
   raise PermissionDeniedError("Permission denied.")
__main__.PermissionDeniedError: Permission denied.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/cg/root/84000/main.py", line 18, in <module>
   raise CompoundException(file_error, permission_error)
__main__.CompoundException: (FileNotFoundError('File not found.'), PermissionDeniedError('Permission denied.'))

Approach 3: Raising an Exception by Using the 'from' Keyword

The third approach utilizes the 'from' catchphrase to raise an unused special case that holds the first exception's traceback. This permits you to supply extra settings without losing the first special case points of interest. Here are the steps −

Algorithm

  • Step 1 − Enclose the code that will raise an exemption inside a try-except piece.

  • Step 2 − Within the try-except block, capture the first exemption utilizing the fitting special case.

  • Step 3 − Raise a modern exception utilizing the 'raise' keyword, taken after by the 'from' catchphrase and the first special case.

Example

#Use try block
try:
   # Code that may raise an exception
   raise ValueError("An error occurred.")
#Utilize except block
except ValueError as original_exception:
   raise TypeError("Invalid type") from original_exception

Output

Traceback (most recent call last):
  File "/home/cg/root/26818/main.py", line 4, in <module>
   raise ValueError("An error occurred.")
ValueError: An error occurred.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/cg/root/26818/main.py", line 7, in <module>
   raise TypeError("Invalid type") from original_exception
TypeError: Invalid type

Conclusion

Raising an exemption to another exemption in Python can be accomplished utilizing different approaches, depending on your particular necessities. These strategies give adaptability and permit you to handle extraordinary scenarios more viably in your Python programs. By understanding and applying these approaches, you'll upgrade the unwavering quality and vigor of your code.

Updated on: 29-Aug-2023

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements