Home » Posts tagged 'Handling specific exceptions in Python'

Tag Archives: Handling specific exceptions in Python

Newly Updated Posts

User Defined Exception in Python

In Python, By defining a new class that inherits from the built-in Exception class or one of its subclasses, you can define your own unique exceptions in Python. An illustration of how to define a user-defined exception in Python is as follows:

class CustomException(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

In the example above, we define a custom exception called CustomException that inherits from the base Exception class. We also override the __init__ method to allow for passing a custom error message when creating an instance of the exception.

Here’s how you can use the custom exception in your code:

def divide_numbers(a, b):
    if b == 0:
        raise CustomException("Division by zero is not allowed.")
    return a / b

try:
    result = divide_numbers(10, 0)
    print("Result:", result)
except CustomException as e:
    print("An error occurred:", e.message)

In the above code, the divide_numbers function checks if the divisor b is zero. If it is, it raises a CustomException with a custom error message. In the try-except block, we catch the CustomException and print the error message.

Output:

An error occurred: Division by zero is not allowed.

By defining and using custom exceptions, you can create more specific and meaningful error handling in your Python programs.

Error and Exception in Python

Python uses errors and exceptions to deal with extraordinary circumstances that could arise while a programme is being executed. The usual flow of the programme is interrupted when an error or exception occurs, and Python raises an error or exception object to specify the error’s kind and specifics. Try-except blocks can be used to handle these mistakes and exceptions. Here is an illustration of how Python handles errors and exceptions:

# Example 1: Handling a specific exception

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 2: Handling multiple exceptions

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 3: Handling any exception (generic exception)

try:
    file = open("nonexistent_file.txt", "r")
    content = file.read()
    file.close()
    print("Content:", content)
except Exception as e:
    print("Error:", str(e))

In the first example, a ,ZeroDivisionError, exception is handled if the user enters zero as the second number for division. In the second example, both 'ValueError and ZeroDivisionError' exceptions are handled, depending on the user’s input. In the third example, a generic Exception is caught, which can handle any type of exception. The 'as' keyword allows you to access the exception object, which can be useful for printing error messages or retrieving specific information about the error.