Playing as a guest? to earn XP and track your progress.
⚡ Exception Handling Quiz
⚡ Exception Handling
Which of the following is a runtime error in Python?
Syntax Error
Logical Error
Exception
Indentation Error
An exception is a runtime error that occurs during execution and disrupts the normal flow of the program.
Which keyword is used to handle exceptions in Python?
catch
handle
except
error
Python uses the except keyword (not catch like Java/C++) to handle exceptions.
Which block in Python's exception handling ALWAYS executes, whether an exception occurs or not?
try
except
else
finally
The finally block always executes regardless of whether an exception was raised or not — it's used for cleanup.
What is the output of the following code?
try:
x = 10 / 0
except ZeroDivisionError:
print("Error")
finally:
print("Done")Error
Done
Error Done
ZeroDivisionError
ZeroDivisionError is caught by except, printing 'Error'. Then finally always runs, printing 'Done'.
Which exception is raised when you try to convert "abc" to an integer using int("abc")?
TypeError
NameError
ValueError
AttributeError
ValueError is raised when a function receives a correct type but an inappropriate value — like passing a non-numeric string to int().
Which exception is raised by 10 / 0?
ValueError
ZeroDivisionError
ArithmeticError
OverflowError
ZeroDivisionError is raised when you attempt to divide a number by zero.
What is the output?
try:
print("A")
except:
print("B")
else:
print("C")
finally:
print("D")A B D
A C D
A D
A B C D
No exception occurs, so try prints 'A', except is skipped, else prints 'C' (no error), finally prints 'D'.
The else block in a try-except structure executes when:
An exception is raised
No exception is raised in the try block
The finally block finishes
Always
The else block runs only when the try block completes without raising any exception.
Which exception is raised when you access lst[10] on a list with only 3 elements?
KeyError
ValueError
IndexError
TypeError
IndexError is raised when a sequence subscript (index) is out of the valid range.
Which exception is raised by d["age"] when the dictionary d does not have the key "age"?
IndexError
ValueError
AttributeError
KeyError
KeyError is raised when a dictionary key is not found in the dictionary.
What does the raise statement do in Python?
Catches an exception
Ignores an exception
Manually triggers an exception
Prints the exception
The raise statement is used to manually trigger (raise) an exception, allowing programmers to enforce custom validation rules.
What is the output?
try:
a = int("hello")
except ValueError:
print("ValueError caught")
except:
print("Other error")ValueError caught
Other error
hello
Error
int("hello") raises a ValueError. The first matching except block catches it and prints 'ValueError caught'.
What is the purpose of as keyword in except ValueError as e?
It renames the exception class
It captures the exception object into variable e
It converts exception to a string
It suppresses the exception
The as keyword captures the exception object into variable e, allowing you to access and print the actual error message.
Which of the following is the correct syntax for catching multiple exceptions with one except clause?
except ValueError, TypeError:
except [ValueError, TypeError]:
except (ValueError, TypeError):
except ValueError | TypeError:
Multiple exception types in a single except clause are grouped using a tuple: except (ValueError, TypeError):
Which exception is raised by print(undefined_variable) when the variable has never been assigned?
ValueError
AttributeError
NameError
TypeError
NameError is raised when a local or global name (variable) is referenced but has not been defined.
Which exception is raised by "hello" + 5?
ValueError
TypeError
NameError
SyntaxError
TypeError is raised when an operation is applied to an object of an inappropriate type — you cannot add a string and an integer.
What will be the output?
def f():
try:
return "from try"
finally:
return "from finally"
print(f())from try
from finally
Error
None
If both try and finally have return statements, the finally block's return overrides the try block's return.
What is the minimum valid structure for exception handling in Python?
try + finally
try + except
try + else
except + finally
The minimum valid structure is just try + except. Both else and finally are optional.
Which exception is raised when you try to open a file that does not exist?
OSError
IOError
FileNotFoundError
PermissionError
FileNotFoundError is raised when a file or directory is requested but cannot be found on disk.
What is the output?
try:
lst = [1, 2, 3]
print(lst[1])
print(lst[5])
print("Done")
except IndexError as e:
print(f"Caught: {e}")
else:
print("No errors!")
finally:
print("Finally!")2 Done No errors! Finally!
2 Caught: list index out of range Finally!
Caught: list index out of range Finally!
2 Caught: list index out of range No errors! Finally!
lst[1] prints 2. lst[5] raises IndexError → jumps to except. else is skipped (exception occurred). finally always runs.
What is an exception in Python?
A syntax mistake in the code
A warning generated at compile time
A runtime error that disrupts normal program flow
A logical mistake in the algorithm
An exception is an event that occurs during execution of a program that disrupts the normal flow of instructions. It is a runtime error represented as an object.
In what order should multiple except clauses be arranged?
General exceptions first, specific exceptions last
Alphabetical order
Specific exceptions first, general exceptions last
Order does not matter
Always put specific exceptions BEFORE general ones. If except Exception: is placed before except ZeroDivisionError:, the specific handler is never reached.
What is the output?
try:
x = int(input())
y = 10 / x
except ZeroDivisionError:
print("Zero!")
except ValueError:
print("Value!")
else:
print("Success")
If input is 2:
Zero!
Value!
Success
Error
Input 2 → int(2) succeeds, 10/2 = 5.0 succeeds. No exception → else block runs → prints 'Success'.
Which of the following exception types is the parent class of most built-in exceptions?
BaseException
RuntimeError
Exception
Error
Exception is the base class for all non-system-exiting exceptions. BaseException is even higher, but Exception is what most built-in exceptions inherit from.
Which exception would be raised by import unicorn?
ModuleNotFoundError
ImportError
NameError
AttributeError
ImportError is raised when an import statement fails. ModuleNotFoundError is a subclass of ImportError.
What is the output?
try:
a = 10
b = 0
c = a / b
print(c)
except ZeroDivisionError:
print("Cannot divide by zero")
except:
print("Some other error")
finally:
print("Always executed")Cannot divide by zero
Always executed
Cannot divide by zero Always executed
Some other error Always executed
a/b raises ZeroDivisionError → first except catches it → prints message. finally always runs → prints 'Always executed'.
What happens when a raise statement is used inside an except block without any argument?
It creates a new exception
It suppresses the current exception
It re-raises the current exception
It exits the program
A bare raise inside an except block re-raises the currently handled exception, allowing it to propagate after logging.
Which of the following is NOT a valid built-in exception in Python?
ZeroDivisionError
NullPointerException
ValueError
KeyError
NullPointerException is a Java exception, not Python. Python uses None instead of null and does not have this exception.
What is the output?
def check(n):
if n < 0:
raise ValueError("Negative not allowed!")
return n * 2
try:
print(check(5))
print(check(-3))
print(check(10))
except ValueError as e:
print(f"Handled: {e}")10 Handled: Negative not allowed!
10 -6 20
Handled: Negative not allowed!
10 Handled: Negative not allowed! 20
check(5) returns 10 (printed). check(-3) raises ValueError → except catches it → prints 'Handled: Negative not allowed!'. check(10) is never reached.
What does a bare except: clause do?
Catches only ValueError
Catches only system exceptions
Catches all exceptions including system exits
Does nothing
A bare except: without specifying any type catches ALL exceptions including KeyboardInterrupt and SystemExit. It should be used cautiously.
Which of the following correctly raises a ValueError with a custom message?
raise ValueError
raise ValueError("Invalid input!")
except ValueError("Invalid input!")
throw ValueError("Invalid input!")
The correct syntax is raise ExceptionType("message"). Always include a descriptive message to explain why the exception was raised.
What is the output?
try:
x = [1, 2, 3]
print(x[0])
except IndexError:
print("Index Error")
else:
print("No Error")1 No Error
1
Index Error
No Error
x[0] = 1, no exception → else runs → prints 'No Error'. Output is: 1 then No Error.
Which type of error occurs when you write primt("Hello") instead of print("Hello")?
Runtime Error
Logical Error
Syntax Error
Compilation Error
primt is syntactically valid Python — it's just a name that doesn't exist. Python raises a NameError (a runtime error / exception) when it tries to execute that line. It is NOT a SyntaxError.
What will be the output?
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: division by zero")
return -1
else:
print("Division successful")
return result
finally:
print("Execution complete")
print(divide(10, 0))Error: division by zero -1
Error: division by zero Execution complete -1
Execution complete Error: division by zero -1
-1 Execution complete
10/0 → except prints 'Error: division by zero'. finally runs before return → prints 'Execution complete'. Then -1 is returned and printed.
Which exception is raised by "hello".push("!")?
TypeError
ValueError
NameError
AttributeError
AttributeError is raised when an attribute reference or assignment fails — strings have no push() method.
How many except clauses can a single try block have?
Only one
Maximum two
Maximum five
As many as needed
A single try block can have as many except clauses as needed — one for each type of exception you want to handle.
What is the primary use of the finally block?
To handle exceptions that were not caught
To run code only when no exception occurs
To perform cleanup operations like closing files
To re-raise exceptions
The finally block is primarily used for cleanup — closing files, releasing network connections, unlocking resources — actions that must happen regardless of errors.
What is the output?
try:
try:
x = 1 / 0
except ValueError:
print("Inner: ValueError")
except ZeroDivisionError:
print("Outer: ZeroDivisionError")Inner: ValueError
Outer: ZeroDivisionError
No output
Error
1/0 raises ZeroDivisionError. The inner except ValueError doesn't match it. The unhandled exception propagates to the outer try-except which catches it with except ZeroDivisionError.
What is the output?
try:
raise ValueError("Bad value")
except TypeError:
print("Type Error")
except ValueError as e:
print(f"Value Error: {e}")
finally:
print("Finished")Type Error Finished
Value Error: Bad value Finished
Bad value Finished
Value Error: Bad value
raise ValueError(...) raises a ValueError. except TypeError doesn't match. except ValueError as e catches it → prints 'Value Error: Bad value'. finally runs → 'Finished'.
What is the output?
try:
x = 5
y = 0
print(x / y)
except (ZeroDivisionError, ValueError) as e:
print(f"Caught: {e}")Caught: division by zero
ZeroDivisionError
0
Error
x/y = 5/0 raises ZeroDivisionError. The tuple except catches both ZeroDivisionError and ValueError. e holds the message 'division by zero'.
Which block will NOT execute if no exception occurs in the try block?
else
finally
except
All of the above
If no exception occurs, the except block is skipped. else runs (no error path), and finally always runs regardless.
What does str(e) give you when e is an exception object?
The exception class name
A human-readable error message
The full traceback
The exception type and message combined
str(e) gives the human-readable error message, e.g. 'division by zero'. Use this for user-facing messages. repr(e) gives the full technical representation.
What is the output?
try:
print(10 / 2)
except ZeroDivisionError:
print("Error")
else:
print("No Error")
finally:
print("Always")5.0 No Error Always
5.0 Always
No Error Always
5.0 Error Always
10/2 = 5.0 succeeds. No exception → except skipped, else runs ('No Error'), finally runs ('Always').
Which of the following exception types has ZeroDivisionError as a subclass?
ValueError
ArithmeticError
LookupError
RuntimeError
In Python's exception hierarchy, ZeroDivisionError is a subclass of ArithmeticError, which in turn inherits from Exception.
What is the output?
try:
n = int("123")
result = 100 / n
except ZeroDivisionError:
print("Divide Error")
except ValueError:
print("Value Error")
else:
print(f"Result: {result}")
finally:
print("End")Result: 0.813... End
Value Error End
Divide Error End
End
int('123') = 123 (no error). 100/123 ≈ 0.813 (no error). else runs → prints 'Result: 0.8130...'. finally runs → prints 'End'.