Python throws errors and exceptions when there is a code gone wrong, which may cause the program to stop abruptly. Python also provides an exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError. A user can create his own error using the exception class.
In Python, exceptions are used to handle runtime errors that occur during program execution. Python provides a set of built-in exceptions, but users can also create their own exceptions, known as user-defined exceptions, to handle specific scenarios.
User-defined exceptions are created by subclassing the built-in Exception class or any of its subclasses. This enables users to define their own set of exceptions that can be raised whenever a specific error occurs in their code.
Here's an example of creating a user-defined exception in Python:
class InvalidInputError(Exception): def __init__(self, message): self.message = message
In the above code, we have created a custom exception called InvalidInputError
by subclassing the built-in Exception
class. We have also defined an __init__()
method to set a custom message for the exception.
Now, we can raise this exception whenever we encounter invalid input in our program. For example:
def divide_numbers(x, y): if y == 0: raise InvalidInputError("Cannot divide by zero") return x / y print(divide_numbers(10, 0)) # Raises InvalidInputError
In the above code, we have used the raise
statement to raise our custom InvalidInputError
exception when the input y
is zero.
By defining custom exceptions, users can make their code more readable and maintainable by handling specific errors in a more elegant way.