Custom Exceptions in Python

Exceptions in Python are events that occur during the execution of a program that disrupt the normal flow of the program's instructions. When an exception occurs, the program will stop executing and instead raise an error message that describes the nature of the problem.

Python Custom Exceptions

User-Defined Exceptions in Python are custom exceptions that are created by the programmer to handle specific errors that may occur in their code. These exceptions are based on the built-in Exception class in Python and can be raised using the raise statement.

By defining their own exceptions, programmers can create more meaningful error messages and provide better guidance to users on how to resolve the issues that have occurred. User-defined exceptions can also be used to control the flow of the program and handle specific error scenarios in a more efficient way.

Custom Exception | Example

Following is an example of how to define and use a custom exception in Python:

class NegativeNumberException(Exception): """Exception raised when a negative number is encountered.""" def __init__(self, value): self.value = value def __str__(self): return "Exception !!! Negative number encountered: {0}".format(self.value)

In the above code, define a custom exception class NegativeNumberException, which is raised when a negative number is encountered. This exception class inherits from the base Exception class, and provides a custom message in the __str__ method to indicate the negative number that was encountered.

def square_root(x): if x < 0: raise NegativeNumberException(x) else: return x**0.5

Then define a function square_root(x), which calculates the square root of a number x. If the input is negative, it raises a NegativeNumberException with the value of x.

try: result = square_root(-4) except NegativeNumberException as e: print(e) else: print(result) #Output: Exception !!! Negative number encountered: -4

In the try-except block, call the square_root function with a negative input -4. This raises a NegativeNumberException, which you can catch in the except block and print the custom error message provided by the exception. If the input was non-negative, the else block is executed and the result is printed.


How to Define Custom Exceptions in Python
Full Source | User-defined Exceptions in Python
class NegativeNumberException(Exception): """Exception raised when a negative number is encountered.""" def __init__(self, value): self.value = value def __str__(self): return "Exception !!! Negative number encountered: {0}".format(self.value) def square_root(x): if x < 0: raise NegativeNumberException(x) else: return x**0.5 try: result = square_root(-4) except NegativeNumberException as e: print(e) else: print(result)

By defining and using custom exceptions, you can provide more specific and informative error messages for our programs, and handle errors more easily.