Python Exception Handling Practice Questions with Solutions

Exception handling helps you manage runtime errors without crashing your program. By using try, except, else, and finally, you can write safer and more reliable Python code. In this practice set, you’ll solve beginner-friendly exception handling questions with complete solutions. Python Exception Handling practice questions with solutions help to understand the concepts.


1. Python Program to Handle Division by Zero

Problem Statement

Write a Python program to divide two numbers and handle the ZeroDivisionError.

Python Solution

try:
    num1 = 20
    num2 = 0

    result = num1 / num2
    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero.")

Sample Output

Cannot divide by zero.

Explanation

The try block contains code that may raise an error. The except block handles the ZeroDivisionError.

Concepts Covered

  • try
  • except
  • ZeroDivisionError

2. Python Program to Handle Invalid User Input

Problem Statement

Write a Python program to accept a number from the user and handle invalid input.

Python Solution

try:
    number = int(input("Enter a number: "))
    print("You entered:", number)

except ValueError:
    print("Please enter a valid integer.")

Sample Output

Enter a number: abc
Please enter a valid integer.

Explanation

If the user enters text instead of a number, Python raises a ValueError.

Concepts Covered

  • ValueError
  • User Input

3. Python Program to Handle File Not Found Error

Problem Statement

Write a Python program to open a file and handle the FileNotFoundError.

Python Solution

try:
    file = open("student.txt", "r")
    print(file.read())
    file.close()

except FileNotFoundError:
    print("File not found.")

Sample Output

File not found.

Explanation

The exception is raised if the specified file does not exist.

Concepts Covered

  • FileNotFoundError

4. Python Program Using try and else

Problem Statement

Write a Python program that divides two numbers and prints a success message using the else block.

Python Solution

try:
    result = 20 / 5

except ZeroDivisionError:
    print("Division by zero is not allowed.")

else:
    print("Result:", result)
    print("Division completed successfully.")

Sample Output

Result: 4.0
Division completed successfully.

Explanation

The else block runs only when no exception occurs.

Concepts Covered

  • else

5. Python Program Using finally

Problem Statement

Write a Python program that always prints "Program Ended" using the finally block.

Python Solution

try:
    number = 10 / 2
    print(number)

except ZeroDivisionError:
    print("Error")

finally:
    print("Program Ended")

Sample Output

5.0
Program Ended

Explanation

The finally block always executes, whether an exception occurs or not.

Concepts Covered

  • finally

6. Python Program to Handle Multiple Exceptions

Problem Statement

Write a Python program to handle both ValueError and ZeroDivisionError.

Python Solution

try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(result)

except ValueError:
    print("Invalid number.")

except ZeroDivisionError:
    print("Cannot divide by zero.")

Sample Output

Enter a number: 0
Cannot divide by zero.

Explanation

Multiple except blocks allow different errors to be handled separately.

Concepts Covered

  • Multiple Exceptions

7. Python Program to Raise a Custom Exception

Problem Statement

Write a Python program that raises an exception if age is less than 18.

Python Solution

age = 16

if age < 18:
    raise Exception("Age must be 18 or above.")

print("Eligible")

Sample Output

Exception: Age must be 18 or above.

Explanation

The raise keyword allows you to create and throw your own exceptions.

Concepts Covered

  • raise

8. Python Program to Catch Any Exception

Problem Statement

Write a Python program to catch any exception using a generic except block.

Python Solution

try:
    number = int("Python")

except Exception as error:
    print("Error:", error)

Sample Output

Error: invalid literal for int() with base 10: 'Python'

Explanation

The generic Exception class catches most runtime errors.

Concepts Covered

  • Exception
  • Exception Object

9. Python Program to Handle IndexError

Problem Statement

Write a Python program to handle an IndexError.

Python Solution

try:
    numbers = [10, 20, 30]

    print(numbers[5])

except IndexError:
    print("Index is out of range.")

Sample Output

Index is out of range.

Explanation

An IndexError occurs when you access a list index that doesn’t exist.

Concepts Covered

  • IndexError

10. Python Program to Handle KeyError

Problem Statement

Write a Python program to handle a KeyError while accessing a dictionary.

Python Solution

student = {
    "name": "John",
    "age": 20
}

try:
    print(student["course"])

except KeyError:
    print("Key not found.")

Sample Output

Key not found.

Explanation

A KeyError occurs when a dictionary key does not exist.

Concepts Covered

  • KeyError

11. Python Program to Handle Multiple Exceptions in a Single Program

Problem Statement

Write a Python program that accepts two numbers from the user and performs division while handling ValueError and ZeroDivisionError exceptions.

Python Solution

try:

    number1 = int(input("Enter First Number: "))
    number2 = int(input("Enter Second Number: "))

    result = number1 / number2

    print("Result =", result)

except ValueError:

    print("Error: Please enter valid integer values.")

except ZeroDivisionError:

    print("Error: Division by zero is not allowed.")

Sample Output

Enter First Number: 20
Enter Second Number: 0

Error: Division by zero is not allowed.

Explanation

The program catches two different exceptions separately:

  • ValueError occurs when the user enters invalid input.
  • ZeroDivisionError occurs when attempting to divide by zero.

Concepts Covered

  • try
  • except
  • Multiple Exceptions
  • User Input Validation

12. Python Program to Use the else Block in Exception Handling

Problem Statement

Write a Python program that performs division and executes the else block only if no exception occurs.

Python Solution

try:

    number1 = int(input("Enter First Number: "))
    number2 = int(input("Enter Second Number: "))

    result = number1 / number2

except ZeroDivisionError:

    print("Cannot divide by zero.")

except ValueError:

    print("Invalid Input.")

else:

    print("Division Successful.")
    print("Result =", result)

Sample Output

Enter First Number: 24
Enter Second Number: 6

Division Successful.
Result = 4.0

Explanation

The else block executes only when the try block completes successfully without raising any exception.

Concepts Covered

  • else Block
  • Exception Handling
  • Input Validation
  • Division

13. Python Program to Demonstrate the finally Block

Problem Statement

Write a Python program that reads a file and ensures it is always closed using the finally block.

Python Solution

file = None

try:

    file = open("sample.txt", "r")

    print(file.read())

except FileNotFoundError:

    print("File not found.")

finally:

    if file:

        file.close()

    print("File operation completed.")

Sample Output

Python Exception Handling Practice

File operation completed.

Explanation

The finally block executes regardless of whether an exception occurs, making it ideal for releasing resources such as files or database connections.

Concepts Covered

  • finally Block
  • File Handling
  • Resource Management
  • Exception Handling

14. Python Program to Handle IndexError While Accessing List Elements

Problem Statement

Write a Python program to safely access a list element by index and handle the IndexError exception.

Python Solution

numbers = [10, 20, 30, 40, 50]

try:

    index = int(input("Enter Index: "))

    print("Value =", numbers[index])

except IndexError:

    print("Error: Index is out of range.")

except ValueError:

    print("Error: Please enter a valid integer.")

Sample Output

Enter Index: 10

Error: Index is out of range.

Explanation

The program prevents the application from crashing when the user enters an index that does not exist in the list.

Concepts Covered

  • IndexError
  • List Handling
  • try-except
  • Safe Data Access

15. Python Program to Handle KeyError in a Dictionary

Problem Statement

Write a Python program that retrieves a value from a dictionary and handles the KeyError exception if the key is not found.

Python Solution

student = {

    "Name": "Rahul",
    "Course": "Python",
    "Marks": 92
}

try:

    key = input("Enter Key: ")

    print(student[key])

except KeyError:

    print("Error: Key does not exist in the dictionary.")

Sample Output

Enter Key: Age

Error: Key does not exist in the dictionary.

Explanation

If the user enters a key that is not available in the dictionary, Python raises a KeyError, which is handled gracefully using the except block.

Concepts Covered

  • KeyError
  • Dictionary
  • Exception Handling
  • User Input Validation

16. Python Program to Raise a Custom Exception for Invalid Age

Problem Statement

Write a Python program that accepts the user’s age. If the age is less than 18, raise an exception stating that the user is not eligible to vote.

Python Solution

try:

    age = int(input("Enter Your Age: "))

    if age < 18:
        raise Exception("You are not eligible to vote.")

    print("You are eligible to vote.")

except Exception as error:

    print("Error:", error)

Sample Output

Enter Your Age: 16

Error: You are not eligible to vote.

Explanation

The raise statement allows developers to generate exceptions manually based on custom conditions. In this example, an exception is raised when the user’s age is below 18.

Concepts Covered

  • raise Statement
  • Exception Handling
  • User Validation
  • Conditional Statements

17. Python Program to Handle TypeError During String and Integer Operations

Problem Statement

Write a Python program that attempts to add a string and an integer, then handles the resulting TypeError.

Python Solution

try:

    name = "Rahul"

    age = 22

    result = name + age

    print(result)

except TypeError:

    print("Error: Cannot add a string and an integer.")

Sample Output

Error: Cannot add a string and an integer.

Explanation

Python raises a TypeError when incompatible data types are used in an operation. The program catches the exception and displays a meaningful error message.

Concepts Covered

  • TypeError
  • Data Types
  • Exception Handling
  • try-except

18. Python Program to Create a Custom Exception Class

Problem Statement

Write a Python program to create a custom exception named InvalidSalaryError. Raise this exception if an employee’s salary is less than ₹15,000.

Python Solution

class InvalidSalaryError(Exception):
    pass

try:

    salary = int(input("Enter Salary: "))

    if salary < 15000:
        raise InvalidSalaryError(
            "Salary must be at least ₹15000."
        )

    print("Salary Accepted.")

except InvalidSalaryError as error:

    print("Error:", error)

Sample Output

Enter Salary: 12000

Error: Salary must be at least ₹15000.

Explanation

The program defines a user-defined exception by inheriting from the built-in Exception class. This is useful for implementing application-specific validation rules.

Concepts Covered

  • Custom Exceptions
  • raise
  • User-defined Exception
  • Inheritance

19. Python Program to Handle FileNotFoundError

Problem Statement

Write a Python program that opens a text file and handles the FileNotFoundError exception if the file does not exist.

Python Solution

try:

    file = open("student_data.txt", "r")

    print(file.read())

    file.close()

except FileNotFoundError:

    print("Error: The specified file does not exist.")

Sample Output

Error: The specified file does not exist.

Explanation

If Python cannot locate the requested file, it raises a FileNotFoundError. The program catches the exception and prevents the application from crashing.

Concepts Covered

  • File Handling
  • FileNotFoundError
  • Exception Handling
  • Safe File Operations

20. Python Program to Validate User Password Using Exception Handling

Problem Statement

Write a Python program that validates a user’s password. Raise an exception if the password is shorter than 8 characters.

Python Solution

try:

    password = input("Enter Password: ")

    if len(password) < 8:

        raise ValueError(
            "Password must contain at least 8 characters."
        )

    print("Password Accepted.")

except ValueError as error:

    print("Error:", error)

Sample Output

Enter Password: pass123

Error: Password must contain at least 8 characters.

Explanation

The program validates the password length. If it does not meet the minimum requirement, a ValueError is raised and handled gracefully.

Concepts Covered

  • ValueError
  • raise Statement
  • Input Validation
  • Exception Handling

21. Python Program to Create a Banking System with Custom Exception Handling

Problem Statement

Write a Python program to simulate a banking system. Raise a custom exception if the withdrawal amount exceeds the available balance.

Python Solution

class InsufficientBalanceError(Exception):
    pass

balance = 10000

try:

    amount = int(input("Enter Withdrawal Amount: "))

    if amount > balance:
        raise InsufficientBalanceError(
            "Insufficient balance in your account."
        )

    balance -= amount

    print("Withdrawal Successful.")
    print("Remaining Balance:", balance)

except InsufficientBalanceError as error:

    print("Error:", error)

Sample Output

Enter Withdrawal Amount: 15000

Error: Insufficient balance in your account.

Explanation

A custom exception is created to represent insufficient account balance. This makes the program more readable and suitable for real-world banking applications.

Concepts Covered

  • Custom Exception
  • raise Statement
  • Banking Application
  • Exception Handling

22. Python Program to Validate Email Address Using Exception Handling

Problem Statement

Write a Python program that validates an email address. Raise an exception if the email does not contain both '@' and '.'.

Python Solution

try:

    email = input("Enter Email Address: ")

    if "@" not in email or "." not in email:

        raise ValueError(
            "Invalid email address."
        )

    print("Email is valid.")

except ValueError as error:

    print("Error:", error)

Sample Output

Enter Email Address: usergmail.com

Error: Invalid email address.

Explanation

The program checks whether the email contains the required symbols. If not, a ValueError is raised with a custom message.

Concepts Covered

  • ValueError
  • Input Validation
  • raise
  • String Operations

23. Python Program to Log Exceptions into a File

Problem Statement

Write a Python program that catches runtime exceptions and stores them in a log file named error_log.txt.

Python Solution

try:

    number = int(input("Enter Number: "))

    result = 100 / number

    print("Result =", result)

except Exception as error:

    with open("error_log.txt", "a") as file:

        file.write(str(error) + "\n")

    print("Exception logged successfully.")

Sample Output

Enter Number: 0

Exception logged successfully.

Sample error_log.txt

division by zero

Explanation

Instead of only displaying the exception, the program records it in a log file. Logging exceptions is a common practice in production applications.

Concepts Covered

  • Exception Logging
  • File Handling
  • try-except
  • Real-world Debugging

24. Python Program to Retry User Input Until Valid Data is Entered

Problem Statement

Write a Python program that repeatedly asks the user to enter an integer until a valid integer is provided.

Python Solution

while True:

    try:

        number = int(input("Enter an Integer: "))

        print("You entered:", number)

        break

    except ValueError:

        print("Invalid input. Please enter a valid integer.")

Sample Output

Enter an Integer: abc

Invalid input. Please enter a valid integer.

Enter an Integer: 25

You entered: 25

Explanation

The program continues prompting the user until a valid integer is entered. This approach is commonly used in interactive applications to ensure reliable input.

Concepts Covered

  • while Loop
  • ValueError
  • Input Validation
  • Exception Handling

25. Python Program to Process Multiple Student Marks with Exception Handling

Problem Statement

Write a Python program to process marks for multiple students. Handle invalid marks and continue processing the remaining students without terminating the program.

Python Solution

students = ["Rahul", "Priya", "Aman"]

for student in students:

    try:

        marks = int(input(f"Enter marks for {student}: "))

        if marks < 0 or marks > 100:

            raise ValueError(
                "Marks must be between 0 and 100."
            )

        print(student, "Marks:", marks)

    except ValueError as error:

        print("Error for", student, ":", error)

Sample Output

Enter marks for Rahul: 95
Rahul Marks: 95

Enter marks for Priya: 120
Error for Priya : Marks must be between 0 and 100.

Enter marks for Aman: 88
Aman Marks: 88

Explanation

Each student’s marks are validated individually. Even if one student’s input is invalid, the program continues processing the remaining students. This is a practical example of robust exception handling in real-world applications.

Concepts Covered

  • Exception Handling
  • ValueError
  • Loops
  • Input Validation
  • Real-World Student Management

Frequently Asked Questions (FAQs)


1. What is Exception Handling in Python?

Exception Handling is a mechanism that allows a Python program to handle runtime errors gracefully without crashing. It uses try, except, else, and finally blocks to detect and manage exceptions.

Example:

try:
    number = int(input("Enter a number: "))
    print(100 / number)

except ZeroDivisionError:
    print("Division by zero is not allowed.")

Concepts Covered

  • Exception Handling
  • try
  • except
  • Runtime Errors

2. What is the difference between a syntax error and an exception?

A Syntax Error occurs when Python cannot understand the program due to incorrect syntax.

An Exception occurs while the program is running, even if the syntax is correct.

Syntax ErrorException
Detected before executionOccurs during execution
Program won’t startProgram starts but encounters an error
Example: Missing colon (:)Example: Division by zero

Understanding this difference helps developers identify and fix errors more efficiently.


3. What is the purpose of the try block?

The try block contains code that might raise an exception. If an exception occurs, Python immediately transfers control to the appropriate except block.

Example:

try:
    number = int(input("Enter Number: "))
    print(50 / number)

except ZeroDivisionError:
    print("Cannot divide by zero.")

The try block is the foundation of Python exception handling.


4. What is the purpose of the else block in exception handling?

The else block executes only if no exception occurs inside the try block.

Example:

try:
    number = int(input("Enter Number: "))

except ValueError:
    print("Invalid Input")

else:
    print("Valid Number:", number)

Using the else block separates normal program logic from exception-handling code, making programs cleaner and easier to understand.


5. What is the purpose of the finally block?

The finally block always executes, whether an exception occurs or not. It is commonly used for cleanup operations such as closing files, releasing resources, or disconnecting from databases.

Example:

try:
    file = open("sample.txt", "r")
    print(file.read())

finally:
    file.close()
    print("File Closed")

The finally block ensures important cleanup tasks are always completed.


6. What is the difference between raise and except?

raiseexcept
Used to manually generate an exceptionUsed to catch and handle an exception
Stops normal execution until handledExecutes when an exception occurs
Used for validationUsed for error recovery

Example:

age = 15

if age < 18:
    raise ValueError("Age must be at least 18.")

Use raise when you want to create your own error conditions.


7. What are custom exceptions in Python?

Custom exceptions are user-defined exception classes created by inheriting from the built-in Exception class. They are useful for handling application-specific errors.

Example:

class InvalidAgeError(Exception):
    pass

try:
    age = 16

    if age < 18:
        raise InvalidAgeError("Not eligible to vote.")

except InvalidAgeError as error:
    print(error)

Custom exceptions improve code readability and make error handling more meaningful.


8. Can one try block have multiple except blocks?

Yes. A single try block can have multiple except blocks to handle different exception types separately.

Example:

try:
    number = int(input("Enter Number: "))
    print(100 / number)

except ValueError:
    print("Invalid Input")

except ZeroDivisionError:
    print("Division by Zero")

This allows your program to provide specific error messages for different problems.


9. What are the most common exceptions in Python?

Some frequently encountered exceptions include:

  • ZeroDivisionError
  • ValueError
  • TypeError
  • IndexError
  • KeyError
  • FileNotFoundError
  • AttributeError
  • NameError
  • ImportError
  • ModuleNotFoundError

Understanding these exceptions helps you write more robust and reliable Python programs.


10. Why is Exception Handling important in Python interviews and real-world projects?

Exception Handling is one of the most important Python topics because it ensures applications can handle unexpected situations without crashing.

Common interview topics include:

  • try, except, else, and finally
  • Multiple exception handling
  • Raising exceptions with raise
  • Custom exceptions
  • User-defined exception classes
  • Exception logging
  • File-related exceptions
  • Nested exception handling
  • Input validation
  • Best practices for error handling

Exception handling is widely used in Web Development, Data Science, Machine Learning, Automation, Banking Systems, E-commerce Applications, APIs, Desktop Applications, Cloud Services, and Enterprise Software. Mastering this topic helps you build secure, stable, and production-ready Python applications while preparing you for technical interviews and real-world development.

Chapter Summary

After completing this chapter, you have learned:

  • try
  • except
  • else
  • finally
  • Handling ZeroDivisionError
  • Handling ValueError
  • Handling FileNotFoundError
  • Handling IndexError
  • Handling KeyError
  • Handling multiple exceptions
  • Raising custom exceptions

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top