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
Difficulty: Foundation
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
Difficulty: Foundation
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
Difficulty: Foundation
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
Difficulty: Foundation
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
Difficulty: Practice
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
Difficulty: Practice
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
Difficulty: Practice
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
Difficulty: Challenge
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
Difficulty: Challenge
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
Difficulty: Challenge
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
Chapter Summary
After completing this chapter, you have learned:
tryexceptelsefinally- 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.
