How do you write a user-defined exception in Python?
Here’s an example of how you can define and use a user-defined exception in Python:
class InvalidInputError(Exception):
"""Exception raised for invalid input."""
def __init__(self, message):
self.message = message
super().__init__(self.message)
def divide_numbers(a, b):
if b == 0:
raise InvalidInputError("Cannot divide by zero.")
return a / b
# Example usage
try:
result = divide_numbers(10, 0)
except InvalidInputError as e:
print("Error:", e.message)
Code language: Python (python)
In this example, we define a custom exception called InvalidInputError
that inherits from the base Exception
class. The exception is raised in the divide_numbers
function when the denominator b
is zero. When the exception is raised, an error message is passed to the exception’s constructor.
In the example usage, we try to divide 10 by 0, which is an invalid operation. The InvalidInputError
exception is raised, and we catch it using a try-except
block. The error message is then printed to the console.
By creating custom exceptions, you can provide more specific and meaningful error messages for different scenarios in your code.
What is user-defined exception and built in exception in Python?
In Python, both user-defined exceptions and built-in exceptions are used to handle and manage errors and exceptional situations in a program.
User-defined exceptions:
These are exceptions that you define yourself by creating a new class. You can create custom exceptions to handle specific errors or exceptional conditions that are relevant to your program. User-defined exceptions are useful when you need to differentiate between different types of errors or provide more specific information about the cause of an exception. You can define your own exception classes by inheriting from the built-in Exception
class or any of its subclasses.
Here’s an example of a user-defined exception:
class InvalidInputError(Exception):
"""Exception raised for invalid input."""
def __init__(self, message):
self.message = message
super().__init__(self.message)
Code language: Python (python)
Built-in exceptions:
These are exceptions that are already defined in the Python language and are available for use without requiring any additional code. Python provides a wide range of built-in exceptions that cover common error scenarios. Some of the commonly used built-in exceptions include ValueError
, TypeError
, IndexError
, KeyError
, FileNotFoundError
, and ZeroDivisionError
, among others. These exceptions are raised when certain predefined errors occur during the execution of a program.
Here’s an example of using a built-in exception:
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero.")
Code language: Python (python)
In this example, the built-in ZeroDivisionError
exception is raised when attempting to divide a number by zero.
Both user-defined exceptions and built-in exceptions are used in error handling to ensure that your program can gracefully handle exceptional situations and provide appropriate feedback or take necessary actions.
Read More;
- Simple Python Script Example [Super Simple!]
- K-means Clustering for Anomaly Detection
- What is f’ Python [With Examples]
- Is Python Similar to R [Easier Than Python?]
- Best Python Library to Detect Language
- How do I write a YAML file in Python?
- What is Statement in Python With Example?
- What is ‘Self’ in Python With Example
- What is Attribute in Python With Example
- Example JSON file for Python [With Explantion]
- What is Token in Python With Example
- List I j in Python [Detailed Examples]