Home » Data Science » Python » Error and Exception in Python

Newly Updated Posts

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.