Error Handling in Python with Example Program

 Program 1: Handling Specific Exceptions with Exception as e

Example Program:

try:
    a = int(input("Enter a number: "))
    b = int(input("Enter another number: "))
    print("Sum:", a + b)
except Exception as e:
    print("Something went wrong:", e)
    
Example Input:
10
abc

Output:
Something went wrong: invalid literal for int() with base 10: 'abc'

Program 2: Handling Invalid Input (Strings Instead of Numbers)

Example Program:

try:
    a = input("Enter a number: ")
    b = input("Enter another number: ")
    print("Concatenation:", a + b)  # This performs string concatenation
except Exception as e:
    print("Something went wrong:", e)
    
Example Input:
10
20

Output:
Concatenation: 1020

Program 3: Handling ValueError for Invalid Conversion

Example Program:

try:
    a = int(input("Enter a number: "))
except ValueError as e:
    print("ValueError:", e)
    
Example Input:
abc

Output:
ValueError: invalid literal for int() with base 10: 'abc'

Program 4: Handling Multiple Exception Types

Example Program:

try:
    a = int(input("Enter a number: "))
    b = int(input("Enter another number: "))
    c = input("Enter a string: ")
    print("Division:", c / a)  # This will cause a TypeError
except ValueError as e:
    print("ValueError:", e)
except TypeError as e:
    print("TypeError:", e)
    
Example Input:
10
5
20

Output:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Program 5: Catching Multiple Exceptions

Example Program:

try:
    a = int(input("Enter a number: "))
    b = int(input("Enter another number: "))
    c = input("Enter a string: ")
    print("Division:", c / a)  # This will raise an exception
    print(d)  # NameError because 'd' is not defined
except ValueError as e:
    print("ValueError:", e)
except TypeError as e:
    print("TypeError:", e)
except Exception as e:
    print("Something went wrong:", e)
    
Example Input:
10
5
20

Output:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Program 6: Using finally Block

Example Program:

try:
    a = int(input("Enter a number: "))
    b = int(input("Enter another number: "))
    c = input("Enter a string: ")
    print("Division:", c / a)
    print(d)  # NameError
except ValueError as e:
    print("ValueError:", e)
except TypeError as e:
    print("TypeError:", e)
except Exception as e:
    print("Something went wrong:", e)
finally:
    print("This block runs no matter what.")
    
Example Input:
10
5
abc

Output:
Something went wrong: unsupported operand type(s) for /: 'str' and 'int'
This block runs no matter what.

Post a Comment

0 Comments