Exception Handling Practice
Handle runtime errors with try, except, else, finally and custom exceptions.
1
Catch Division by Zero
Easy
Write a program that divides two integers and catches ZeroDivisionError, printing 'Cannot divide by zero'.
Input Format
First line: a. Second line: b.
Output Format
Print the quotient, or the error message.
Sample Test Cases
|
Sample Input 1
10 0 |
Sample Output 1
Cannot divide by zero |
|
Sample Input 2
4 0 |
Sample Output 2
Cannot divide by zero |
|
Sample Input 3
8 2 |
Sample Output 3
4.0 |
2
Catch ValueError on int()
Easy
Write a program that converts input to int and catches ValueError, printing 'Invalid number'.
Input Format
A single line containing the input.
Output Format
Print the integer, or 'Invalid number'.
Sample Test Cases
|
Sample Input 1
abc |
Sample Output 1
Invalid number |
|
Sample Input 2
42 |
Sample Output 2
42 |
|
Sample Input 3
1.5 |
Sample Output 3
Invalid number |
3
Try-Except with Multiple Values
Easy
Write a program that reads two numbers and prints their sum, catching any input error.
Input Format
A single line containing two values.
Output Format
Print the sum, or 'Invalid input'.
Sample Test Cases
|
Sample Input 1
2 3 |
Sample Output 1
5 |
|
Sample Input 2
10 x |
Sample Output 2
Invalid input |
|
Sample Input 3
1 2 3 |
Sample Output 3
6 |
4
Simple try-except
Easy
Write a program that accesses an out-of-range list index and catches IndexError.
Input Format
No input (list [1,2,3], index 5).
Output Format
Print 'Index out of range'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Index out of range |
|
Sample Input 2
|
Sample Output 2
Index out of range |
|
Sample Input 3
|
Sample Output 3
Index out of range |
5
Catch KeyError
Easy
Write a program that looks up a missing key in a dict and catches KeyError.
Input Format
A single line containing a key to look up (dict = {'a':1,'b':2}).
Output Format
Print the value, or 'Key not found'.
Sample Test Cases
|
Sample Input 1
z |
Sample Output 1
Key not found |
|
Sample Input 2
a |
Sample Output 2
1 |
|
Sample Input 3
b |
Sample Output 3
2 |
6
Catch TypeError
Easy
Write a program that tries to add a string and an integer and catches TypeError.
Input Format
No input.
Output Format
Print 'Type error occurred'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Type error occurred |
|
Sample Input 2
|
Sample Output 2
Type error occurred |
|
Sample Input 3
|
Sample Output 3
Type error occurred |
7
Try-Except-Finally
Easy
Write a program that tries to convert to int and always prints 'Done' in finally.
Input Format
A single line containing the input.
Output Format
Print the int or error, then 'Done'.
Sample Test Cases
|
Sample Input 1
5 |
Sample Output 1
5 Done |
|
Sample Input 2
abc |
Sample Output 2
Invalid number Done |
|
Sample Input 3
7 |
Sample Output 3
7 Done |
8
Catch Multiple Exceptions
Easy
Write a program that catches both ValueError and ZeroDivisionError.
Input Format
First line: a. Second line: b.
Output Format
Print the result, or the specific error message.
Sample Test Cases
|
Sample Input 1
5 0 |
Sample Output 1
Cannot divide by zero |
|
Sample Input 2
7 0 |
Sample Output 2
Cannot divide by zero |
|
Sample Input 3
6 3 |
Sample Output 3
2.0 |
9
Exception with else Block
Easy
Write a program with try-except-else that prints 'No error' when the conversion succeeds.
Input Format
A single line containing an integer string.
Output Format
Print the integer, then 'No error'.
Sample Test Cases
|
Sample Input 1
42 |
Sample Output 1
42 No error |
|
Sample Input 2
abc |
Sample Output 2
Invalid number |
|
Sample Input 3
7 |
Sample Output 3
7 No error |
10
Handle File Not Found
Easy
Write a program that tries to open 'missing.txt' and catches FileNotFoundError.
Input Format
No input.
Output Format
Print 'File not found'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
File not found |
|
Sample Input 2
|
Sample Output 2
File not found |
|
Sample Input 3
|
Sample Output 3
File not found |
1
Raising an Exception
Medium
Write a program that raises ValueError with message 'Negative not allowed' if input is negative.
Input Format
A single line containing an integer.
Output Format
Print the number, or the error message.
Sample Test Cases
|
Sample Input 1
-5 |
Sample Output 1
Negative not allowed |
|
Sample Input 2
10 |
Sample Output 2
10 |
|
Sample Input 3
-1 |
Sample Output 3
Negative not allowed |
2
Custom Exception Class
Medium
Write a custom exception class NegativeError that inherits Exception, and raise it for negative input.
Input Format
A single line containing an integer.
Output Format
Print 'Custom error: Negative value', or the number.
Sample Test Cases
|
Sample Input 1
-3 |
Sample Output 1
Custom error: Negative value |
|
Sample Input 2
5 |
Sample Output 2
5 |
|
Sample Input 3
-1 |
Sample Output 3
Custom error: Negative value |
3
Try-Except-Else-Finally
Medium
Write a program that divides two numbers and prints 'Success' in else and 'Cleanup done' in finally.
Input Format
First line: a. Second line: b.
Output Format
Print the quotient, 'Success', and 'Cleanup done'.
Sample Test Cases
|
Sample Input 1
8 2 |
Sample Output 1
4.0 Success Cleanup done |
|
Sample Input 2
10 0 |
Sample Output 2
Cannot divide by zero Cleanup done |
|
Sample Input 3
9 3 |
Sample Output 3
3.0 Success Cleanup done |
4
Nested Try-Except
Medium
Write a program with an inner try that converts a value and an outer try that performs division.
Input Format
First line: a. Second line: b.
Output Format
Print the result or appropriate error message.
Sample Test Cases
|
Sample Input 1
10 0 |
Sample Output 1
Cannot divide by zero |
|
Sample Input 2
abc 2 |
Sample Output 2
Cannot divide by zero |
|
Sample Input 3
10 5 |
Sample Output 3
2.0 |
5
Catch and Reraise
Medium
Write a program that catches ZeroDivisionError, prints 'Caught', then re-raises it.
Input Format
First line: a. Second line: b (0).
Output Format
Print 'Caught' and the re-raised error message.
Sample Test Cases
|
Sample Input 1
5 0 |
Sample Output 1
Caught Cannot divide by zero |
|
Sample Input 2
5 0 |
Sample Output 2
Caught Cannot divide by zero |
|
Sample Input 3
10 2 |
Sample Output 3
Caught 5.0 |
6
Exception Hierarchy
Medium
Write a program that catches ArithmeticError (parent of ZeroDivisionError) for division by zero.
Input Format
First line: a. Second line: b.
Output Format
Print 'Arithmetic error caught'.
Sample Test Cases
|
Sample Input 1
4 0 |
Sample Output 1
Arithmetic error caught |
|
Sample Input 2
9 0 |
Sample Output 2
Arithmetic error caught |
|
Sample Input 3
8 4 |
Sample Output 3
Arithmetic error caught 2.0 |
7
Index Error with Details
Medium
Write a program that accesses list index out of range and prints the valid index range instead.
Input Format
No input (list [10,20,30], index 5).
Output Format
Print 'Valid indices: 0 to 2'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Valid indices: 0 to 2 |
|
Sample Input 2
|
Sample Output 2
Valid indices: 0 to 2 |
|
Sample Input 3
|
Sample Output 3
Valid indices: 0 to 2 |
8
Attribute Error Handling
Medium
Write a program that accesses a non-existent attribute on an object and catches AttributeError.
Input Format
No input (empty class with no attributes, access .missing).
Output Format
Print 'Attribute not found'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Attribute not found |
|
Sample Input 2
|
Sample Output 2
Attribute not found |
|
Sample Input 3
|
Sample Output 3
Attribute not found |
9
Chained Exceptions
Medium
Write a program that catches ValueError and re-raises it as RuntimeError with 'from e'.
Input Format
A single line containing the input.
Output Format
Print 'Converted to RuntimeError'.
Sample Test Cases
|
Sample Input 1
abc |
Sample Output 1
Converted to RuntimeError |
|
Sample Input 2
5 |
Sample Output 2
Converted to RuntimeError |
|
Sample Input 3
x |
Sample Output 3
Converted to RuntimeError |
10
Try-Except with Loop
Medium
Write a program that keeps asking for a valid integer until one is entered (simulate: use 2 attempts from input).
Input Format
Two lines: first invalid value, then valid value.
Output Format
Print the valid integer.
Sample Test Cases
|
Sample Input 1
abc 42 |
Sample Output 1
42 |
|
Sample Input 2
x 10 |
Sample Output 2
10 |
|
Sample Input 3
a b 5 |
Sample Output 3
5 |
1
Bank Withdrawal with Custom Errors
Hard
Write a class BankAccount with withdraw(amount) that raises custom errors for negative amount and insufficient balance.
Input Format
First line: balance. Second line: withdrawal.
Output Format
Print 'Withdrawn' or the specific error message.
Sample Test Cases
|
Sample Input 1
100 150 |
Sample Output 1
Insufficient balance |
|
Sample Input 2
500 100 |
Sample Output 2
Withdrawn |
|
Sample Input 3
100 150 |
Sample Output 3
Insufficient balance |
2
File Processing with Errors
Hard
Write a program that reads a filename from input and prints 'File opened' if it exists, catching FileNotFoundError and PermissionError.
Input Format
A single line containing a filename.
Output Format
Print the appropriate message.
Sample Test Cases
|
Sample Input 1
missing.txt |
Sample Output 1
File not found |
|
Sample Input 2
data.txt |
Sample Output 2
File not found |
|
Sample Input 3
missing.csv |
Sample Output 3
File not found |
3
Custom Exception with Attributes
Hard
Write a custom exception InvalidAgeError that carries the age value, and raise it for age outside 0-150.
Input Format
A single line containing the age.
Output Format
Print 'Invalid age: [age]' or the age.
Sample Test Cases
|
Sample Input 1
200 |
Sample Output 1
Invalid age: 200 |
|
Sample Input 2
25 |
Sample Output 2
25 |
|
Sample Input 3
-5 |
Sample Output 3
Invalid age: -5 |
4
Retry Logic with Exceptions
Hard
Write a program that attempts an operation up to 3 times, catching exceptions and printing the attempt number.
Input Format
A single line containing a value that fails twice then succeeds.
Output Format
Print attempt numbers and final success.
Sample Test Cases
|
Sample Input 1
0 |
Sample Output 1
Attempt 1 failed Attempt 2 failed Success |
|
Sample Input 2
0 0 1 |
Sample Output 2
Attempt 1 failed Attempt 2 failed Success |
|
Sample Input 3
5 |
Sample Output 3
Success |
5
Assertion for Validation
Hard
Write a program that uses assert to check that a number is positive, catching AssertionError.
Input Format
A single line containing an integer.
Output Format
Print the number, or 'Assertion failed'.
Sample Test Cases
|
Sample Input 1
-1 |
Sample Output 1
Assertion failed |
|
Sample Input 2
5 |
Sample Output 2
5 |
|
Sample Input 3
0 |
Sample Output 3
Assertion failed |
6
Exception in OOP Methods
Hard
Write a class Calculator with divide(a, b) that raises ZeroDivisionError with a custom message.
Input Format
First line: a. Second line: b.
Output Format
Print the result, or the error message.
Sample Test Cases
|
Sample Input 1
6 0 |
Sample Output 1
Cannot divide by zero |
|
Sample Input 2
9 3 |
Sample Output 2
3.0 |
|
Sample Input 3
9 0 |
Sample Output 3
Cannot divide by zero |
7
Multi-Layer Error Propagation
Hard
Write functions inner() that raises ValueError, and outer() that catches it and prints 'Handled in outer'.
Input Format
No input.
Output Format
Print 'Handled in outer'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Handled in outer |
|
Sample Input 2
|
Sample Output 2
Handled in outer |
|
Sample Input 3
|
Sample Output 3
Handled in outer |
8
Cleanup with finally (Resource)
Hard
Write a program that simulates opening a resource, raises an exception, and closes the resource in finally.
Input Format
A single line containing 1 to trigger the error, else 0.
Output Format
Print 'Resource acquired', error message if triggered, and 'Resource released'.
Sample Test Cases
|
Sample Input 1
1 |
Sample Output 1
Resource acquired Error occurred Resource released |
|
Sample Input 2
0 |
Sample Output 2
Resource acquired Resource released |
|
Sample Input 3
1 |
Sample Output 3
Resource acquired Error occurred Resource released |
9
User-Defined Error Hierarchy
Hard
Write base exception AppError and derived NetworkError and DataError. Raise NetworkError and catch AppError.
Input Format
A single line containing 'network' or 'data'.
Output Format
Print the caught error message.
Sample Test Cases
|
Sample Input 1
network |
Sample Output 1
Network error occurred |
|
Sample Input 2
data |
Sample Output 2
Data error occurred |
|
Sample Input 3
network |
Sample Output 3
Network error occurred |
10
Convert Exception to Message
Hard
Write a program that reads two numbers, attempts division, and converts any exception to a friendly message using str(e).
Input Format
First line: a. Second line: b.
Output Format
Print the friendly error message or the quotient.
Sample Test Cases
|
Sample Input 1
10 0 |
Sample Output 1
division by zero |
|
Sample Input 2
5 2 |
Sample Output 2
2.5 |
|
Sample Input 3
5 0 |
Sample Output 3
division by zero |
Competitive MCQs — Exception Handling
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score
0/ 33
Q1
Which keyword starts a block that may raise an error?
Correct!
Wrong — correct answer is .
Code that may fail goes inside a try block.
Q2
Which keyword handles an exception in Python?
Correct!
Wrong — correct answer is .
Python uses except to catch errors (catch is used in Java/JS).
Q3
What is the output of this code?
python
1
2
3
4
5
6
2
3
4
5
6
try:
print(10 / 0)
except ZeroDivisionError:
print("Error")
else:
print("OK")Correct!
Wrong — correct answer is .
10 / 0 raises ZeroDivisionError, caught by except → "Error".
Q4
What is the output of this code?
try:
print(10 / 0)
except ZeroDivisionError:
print("Error")
else:
print("OK")
try:
print(10 / 0)
except ZeroDivisionError:
print("Error")
else:
print("OK")
Correct!
Wrong — correct answer is .
10 / 0 raises ZeroDivisionError, caught by except → "Error".
Q5
Which block ALWAYS runs whether or not an exception occurs?
Correct!
Wrong — correct answer is .
finally executes no matter what happens in try/except.
Q6
What is the output of this code?
python
1
2
3
4
5
6
2
3
4
5
6
try:
x = int("abc")
except ValueError:
print("Bad value")
except TypeError:
print("Bad type")Correct!
Wrong — correct answer is .
int("abc") raises ValueError, matched by the first except.
Q7
What is the output of this code?
try:
x = int("abc")
except ValueError:
print("Bad value")
except TypeError:
print("Bad type")
try:
x = int("abc")
except ValueError:
print("Bad value")
except TypeError:
print("Bad type")
Correct!
Wrong — correct answer is .
int("abc") raises ValueError, matched by the first except.
Q8
Which is the base class for all built-in exceptions?
Correct!
Wrong — correct answer is .
All built-in exceptions derive from Exception (subclass of BaseException).
Q9
What does raise do?
Correct!
Wrong — correct answer is .
raise Exception("msg") throws an error on purpose.
Q10
What is the output of this code?
python
1
2
3
4
2
3
4
try:
print("A")
finally:
print("B")Correct!
Wrong — correct answer is .
Both lines run; finally needs no exception to execute.
Q11
What is the output of this code?
try:
print("A")
finally:
print("B")
try:
print("A")
finally:
print("B")
Correct!
Wrong — correct answer is .
Both lines run; finally needs no exception to execute.
Q12
What is the purpose of the else clause in try-except-else?
Correct!
Wrong — correct answer is .
else runs when the try block completes without raising.
Q13
Which of the following is an unchecked (runtime) error in Python?
Correct!
Wrong — correct answer is .
KeyError is raised at runtime when a dict key is missing.
Q14
What is the output of this code?
try:
print(1 / 0)
except ZeroDivisionError as e:
print("caught")
print("done")
try:
print(1 / 0)
except ZeroDivisionError as e:
print("caught")
print("done")
Correct!
Wrong — correct answer is .
The exception is caught, prints "caught", then execution continues with "done".
Q15
Which clause captures the exception object?
Correct!
Wrong — correct answer is .
The as e syntax binds the exception instance for inspection.
Q16
What is the output of this code?
try:
print(int("x"))
except ValueError:
print("V")
except Exception:
print("E")
try:
print(int("x"))
except ValueError:
print("V")
except Exception:
print("E")
Correct!
Wrong — correct answer is .
ValueError is caught first; the general Exception handler is skipped.
Q17
What is the output of this code?
try:
x = [1][5]
except IndexError:
print("Index")
try:
x = [1][5]
except IndexError:
print("Index")
Correct!
Wrong — correct answer is .
Accessing index 5 of a 1-element list raises IndexError.
Q18
What does the finally block guarantee?
Correct!
Wrong — correct answer is .
finally always runs for cleanup, even with return/break.
Q19
What is the output of this code?
def f():
try:
return 1
finally:
print("clean")
print(f())
def f():
try:
return 1
finally:
print("clean")
print(f())
Correct!
Wrong — correct answer is .
finally runs before the function returns, printing "clean", then f() returns 1.
Q20
What does raise ValueError("bad") do?
Correct!
Wrong — correct answer is .
raise creates and throws the exception with the given message.
Q21
What is the output of this code?
try:
raise TypeError("t")
except TypeError:
print("Type")
try:
raise TypeError("t")
except TypeError:
print("Type")
Correct!
Wrong — correct answer is .
The manually raised TypeError is caught and prints "Type".
Q22
Which exception is raised for a missing dictionary key?
Correct!
Wrong — correct answer is .
d["missing"] raises KeyError when the key is absent.
Q23
What is the output of this code?
try:
raise KeyError("k")
except KeyError:
print("missing key")
try:
raise KeyError("k")
except KeyError:
print("missing key")
Correct!
Wrong — correct answer is .
The raised KeyError is caught, so the handler prints "missing key".
Q24
Which is the parent of ZeroDivisionError?
Correct!
Wrong — correct answer is .
ZeroDivisionError inherits from ArithmeticError.
Q25
What is the output of this code?
try:
pass
except:
print("never")
else:
print("ok")
try:
pass
except:
print("never")
else:
print("ok")
Correct!
Wrong — correct answer is .
With no exception, the else clause runs and prints "ok".
Q26
What is a bare except: clause?
Correct!
Wrong — correct answer is .
except: catches all exceptions; it is discouraged for hiding bugs.
Q27
What is the output of this code?
try:
x = "5"
print(int(x))
except ValueError:
print("V")
else:
print("OK")
try:
x = "5"
print(int(x))
except ValueError:
print("V")
else:
print("OK")
Correct!
Wrong — correct answer is .
int("5") succeeds printing 5, then the else prints "OK".
Q28
Which exception occurs when calling a method on None?
Correct!
Wrong — correct answer is .
None has no methods, so None.upper() raises AttributeError.
Q29
What is the output of this code?
try:
print(undefined_name)
except NameError:
print("N")
try:
print(undefined_name)
except NameError:
print("N")
Correct!
Wrong — correct answer is .
An unknown name raises NameError, caught and printed as "N".
Q30
What does the raise keyword without arguments do inside an except block?
Correct!
Wrong — correct answer is .
Bare raise propagates the exception currently being handled.
Q31
What is the output of this code?
try:
raise Exception("boom")
except Exception as e:
print(str(e))
try:
raise Exception("boom")
except Exception as e:
print(str(e))
Correct!
Wrong — correct answer is .
The message "boom" is printed through str(e).
Q32
Which block should close files or release resources?
Correct!
Wrong — correct answer is .
finally is the right place for guaranteed cleanup.
Q33
What is the output of this code?
try:
print("A")
except:
print("B")
finally:
print("C")
try:
print("A")
except:
print("B")
finally:
print("C")
Correct!
Wrong — correct answer is .
try prints A, no error occurs, and finally always prints C.