User-defined 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:
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.
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.
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.
Full Source | User-defined Exceptions in Python
By defining and using custom exceptions, you can provide more specific and informative error messages for our programs, and handle errors more easily.