Exit Chapter 04 · ⚡ Exception Handling — Quiz

Playing as a guest? to earn XP and track your progress.

Question 1 of 45 0 correct so far

⚡ Exception Handling Quiz

Q1.

Which of the following is a runtime error in Python?

Explanation

An exception is a runtime error that occurs during execution and disrupts the normal flow of the program.

Q2.

Which keyword is used to handle exceptions in Python?

Explanation

Python uses the except keyword (not catch like Java/C++) to handle exceptions.

Q3.

Which block in Python's exception handling ALWAYS executes, whether an exception occurs or not?

Explanation

The finally block always executes regardless of whether an exception was raised or not — it's used for cleanup.

Q4.

What is the output of the following code?

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Error")
finally:
    print("Done")
Explanation

ZeroDivisionError is caught by except, printing 'Error'. Then finally always runs, printing 'Done'.

Q5.

Which exception is raised when you try to convert "abc" to an integer using int("abc")?

Explanation

ValueError is raised when a function receives a correct type but an inappropriate value — like passing a non-numeric string to int().

Q6.

Which exception is raised by 10 / 0?

Explanation

ZeroDivisionError is raised when you attempt to divide a number by zero.

Q7.

What is the output?

try:
    print("A")
except:
    print("B")
else:
    print("C")
finally:
    print("D")
Explanation

No exception occurs, so try prints 'A', except is skipped, else prints 'C' (no error), finally prints 'D'.

Q8.

The else block in a try-except structure executes when:

Explanation

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

Q9.

Which exception is raised when you access lst[10] on a list with only 3 elements?

Explanation

IndexError is raised when a sequence subscript (index) is out of the valid range.

Q10.

Which exception is raised by d["age"] when the dictionary d does not have the key "age"?

Explanation

KeyError is raised when a dictionary key is not found in the dictionary.

Q11.

What does the raise statement do in Python?

Explanation

The raise statement is used to manually trigger (raise) an exception, allowing programmers to enforce custom validation rules.

Q12.

What is the output?

try:
    a = int("hello")
except ValueError:
    print("ValueError caught")
except:
    print("Other error")
Explanation

int("hello") raises a ValueError. The first matching except block catches it and prints 'ValueError caught'.

Q13.

What is the purpose of as keyword in except ValueError as e?

Explanation

The as keyword captures the exception object into variable e, allowing you to access and print the actual error message.

Q14.

Which of the following is the correct syntax for catching multiple exceptions with one except clause?

Explanation

Multiple exception types in a single except clause are grouped using a tuple: except (ValueError, TypeError):

Q15.

Which exception is raised by print(undefined_variable) when the variable has never been assigned?

Explanation

NameError is raised when a local or global name (variable) is referenced but has not been defined.

Q16.

Which exception is raised by "hello" + 5?

Explanation

TypeError is raised when an operation is applied to an object of an inappropriate type — you cannot add a string and an integer.

Q17.

What will be the output?

def f():
    try:
        return "from try"
    finally:
        return "from finally"

print(f())
Explanation

If both try and finally have return statements, the finally block's return overrides the try block's return.

Q18.

What is the minimum valid structure for exception handling in Python?

Explanation

The minimum valid structure is just try + except. Both else and finally are optional.

Q19.

Which exception is raised when you try to open a file that does not exist?

Explanation

FileNotFoundError is raised when a file or directory is requested but cannot be found on disk.

Q20.

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!")
Explanation

lst[1] prints 2. lst[5] raises IndexError → jumps to except. else is skipped (exception occurred). finally always runs.

Q21.

What is an exception in Python?

Explanation

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.

Q22.

In what order should multiple except clauses be arranged?

Explanation

Always put specific exceptions BEFORE general ones. If except Exception: is placed before except ZeroDivisionError:, the specific handler is never reached.

Q23.

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:

Explanation

Input 2 → int(2) succeeds, 10/2 = 5.0 succeeds. No exception → else block runs → prints 'Success'.

Q24.

Which of the following exception types is the parent class of most built-in exceptions?

Explanation

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.

Q25.

Which exception would be raised by import unicorn?

Explanation

ImportError is raised when an import statement fails. ModuleNotFoundError is a subclass of ImportError.

Q26.

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")
Explanation

a/b raises ZeroDivisionError → first except catches it → prints message. finally always runs → prints 'Always executed'.

Q27.

What happens when a raise statement is used inside an except block without any argument?

Explanation

A bare raise inside an except block re-raises the currently handled exception, allowing it to propagate after logging.

Q28.

Which of the following is NOT a valid built-in exception in Python?

Explanation

NullPointerException is a Java exception, not Python. Python uses None instead of null and does not have this exception.

Q29.

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}")
Explanation

check(5) returns 10 (printed). check(-3) raises ValueError → except catches it → prints 'Handled: Negative not allowed!'. check(10) is never reached.

Q30.

What does a bare except: clause do?

Explanation

A bare except: without specifying any type catches ALL exceptions including KeyboardInterrupt and SystemExit. It should be used cautiously.

Q31.

Which of the following correctly raises a ValueError with a custom message?

Explanation

The correct syntax is raise ExceptionType("message"). Always include a descriptive message to explain why the exception was raised.

Q32.

What is the output?

try:
    x = [1, 2, 3]
    print(x[0])
except IndexError:
    print("Index Error")
else:
    print("No Error")
Explanation

x[0] = 1, no exception → else runs → prints 'No Error'. Output is: 1 then No Error.

Q33.

Which type of error occurs when you write primt("Hello") instead of print("Hello")?

Explanation

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.

Q34.

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))
Explanation

10/0 → except prints 'Error: division by zero'. finally runs before return → prints 'Execution complete'. Then -1 is returned and printed.

Q35.

Which exception is raised by "hello".push("!")?

Explanation

AttributeError is raised when an attribute reference or assignment fails — strings have no push() method.

Q36.

How many except clauses can a single try block have?

Explanation

A single try block can have as many except clauses as needed — one for each type of exception you want to handle.

Q37.

What is the primary use of the finally block?

Explanation

The finally block is primarily used for cleanup — closing files, releasing network connections, unlocking resources — actions that must happen regardless of errors.

Q38.

What is the output?

try:
    try:
        x = 1 / 0
    except ValueError:
        print("Inner: ValueError")
except ZeroDivisionError:
    print("Outer: ZeroDivisionError")
Explanation

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.

Q39.

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")
Explanation

raise ValueError(...) raises a ValueError. except TypeError doesn't match. except ValueError as e catches it → prints 'Value Error: Bad value'. finally runs → 'Finished'.

Q40.

What is the output?

try:
    x = 5
    y = 0
    print(x / y)
except (ZeroDivisionError, ValueError) as e:
    print(f"Caught: {e}")
Explanation

x/y = 5/0 raises ZeroDivisionError. The tuple except catches both ZeroDivisionError and ValueError. e holds the message 'division by zero'.

Q41.

Which block will NOT execute if no exception occurs in the try block?

Explanation

If no exception occurs, the except block is skipped. else runs (no error path), and finally always runs regardless.

Q42.

What does str(e) give you when e is an exception object?

Explanation

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.

Q43.

What is the output?

try:
    print(10 / 2)
except ZeroDivisionError:
    print("Error")
else:
    print("No Error")
finally:
    print("Always")
Explanation

10/2 = 5.0 succeeds. No exception → except skipped, else runs ('No Error'), finally runs ('Always').

Q44.

Which of the following exception types has ZeroDivisionError as a subclass?

Explanation

In Python's exception hierarchy, ZeroDivisionError is a subclass of ArithmeticError, which in turn inherits from Exception.

Q45.

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")
Explanation

int('123') = 123 (no error). 100/123 ≈ 0.813 (no error). else runs → prints 'Result: 0.8130...'. finally runs → prints 'End'.