Python · Errors and Exceptions
Quizz
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Quiz: Which Error Type?
What error occurs when you try to use a variable that was never created?
print(codemon_power)
# codemon_power was never defined!
Options
• ```NameError```
• ```ValueError```
• ```TypeError```
• ```KeyError```
Hint : This error happens when Python doesn't recognize a variable name because it was never created.
Exercise 2 — Quiz: Type Conversion Error
Which line will cause a
ValueError
?
a = int("100")
b = int("25.5")
c = int("Aquachu")
d = str(100)
Options
• Line ```c``` - ```int("Aquachu")```
• Line ```b``` - ```int("25.5")```
• Both ```b``` and ```c```
• Line ```a``` - ```int("100")```
Hint : int() can only convert strings that contain whole numbers. Think about which strings are not valid integers.
Exercise 3 — Quiz: Match Code to Error Type
Match each code snippet with the error it will produce:
Items to match
• print(undefined_var)
• result = 10 / 0
• "text" + 5
• stats = {"hp": 100}
stats["attack"]
Definitions
• NameError
• ZeroDivisionError
• TypeError
• KeyError
Exercise 4 — Quiz: Dictionary Access Error
What will happen when this code runs?
codemon = {"name": "Aquachu", "level": 15}
print(codemon["name"])
print(codemon["type"])
Options
• Prints "Aquachu" then raises ```KeyError```
• Prints "Aquachu" then prints ```None```
• Raises ```KeyError``` immediately
• Prints both values successfully
Hint : The first print works because "name" exists. What happens when we try to access a key that doesn't exist?
Exercise 5 — Quiz: Syntax vs Runtime Error
Which of these is a runtime error, not a syntax error?
Options
• ```ZeroDivisionError``` when dividing by zero
• Missing colon after ```if``` statement
• Incorrect indentation
• Misspelled keyword like ```prnit``` instead of ```print```
Hint : Runtime errors occur during program execution. Syntax errors are detected before the code runs.
Exercise 6 — Quiz: Exception Recovery
What happens to code AFTER a try/except block if an exception was caught?
try:
result = 10 / 0
except ZeroDivisionError:
print("Error handled")
result = 0
print(f"Result: {result}")
print("Program continues")
Options
• The program continues normally and executes the code after the try/except
• The program stops immediately after the except block
• The program skips all remaining code in the file
• The program restarts from the beginning
Hint : Think about the purpose of exception handling - it's meant to prevent crashes and allow the program to continue.
Exercise 7 — Quiz: Exception Handling Flow
What will be printed when this code runs?
try:
result = 10 / 2
print("Division successful")
except ZeroDivisionError:
print("Cannot divide by zero")
print("Program continues")
Options
• "Division successful" and "Program continues"
• Only "Program continues"
• "Cannot divide by zero" and "Program continues"
• Only "Division successful"
Hint : The division is valid (10/2), so no exception occurs. What executes when there's no error?
Exercise 8 — Quiz: Understanding Error Messages
What information does a Python error message typically include?
Options
• The error type, line number, and a description of what went wrong
• Only the line number where the error occurred
• Only the error type without any details
• A suggestion for how to fix the code
Hint : Think about what you see in the terminal when an error occurs - there's usually multiple pieces of useful information.
Exercise 9 — Quiz: Program Behavior Without Exception Handling
What happens if an exception occurs and there's NO try/except to handle it?
Options
• The program crashes and stops immediately
• The error is ignored and the program continues
• Python automatically fixes the error
• The program asks the user what to do
Hint : Think about what you've seen when running code with errors before learning about exception handling.
Exercise 10 — Quiz: Handle Division Error
Complete the code to safely calculate damage, using 0 if division fails:
attack = 100
defense = 0
____:
damage = attack / defense
____:
damage = 0
print(f"Damage: {damage}")
Options: try except if catch handle error
Hint : Use the basic try/except structure to catch the division by zero error.
Exercise 11 — Quiz: Catch Specific ValueError
Complete the code to catch the exception that will happen when converting a non-numeric string to an integer:
try:
level = int("not a number")
except ____:
print("Please enter a valid number!")
level = 1
Options: ValueError Exception TypeError Error ZeroDivisionError KeyError
Hint : What specific error occurs when converting an invalid string to int?
Exercise 12 — Quiz: Exception Message Access
What does the
as e
syntax do in exception handling?
try:
result = int("abc")
except ValueError as e:
print(f"Error: {e}")
Options
• Stores the exception object in variable ```e``` so you can access the error message
• Prevents the exception from being raised
• Creates a new error called ```e```
• Makes the exception handling optional
Hint : Think about why you might want to give the exception a variable name.
Exercise 13 — Quiz: Match Exception to Situation
Match each situation with the specific exception you should catch:
Items to match
• Converting user input to integer
• Dividing by a variable that might be zero
• Accessing a dictionary key that might not exist
• Accessing a list index that might be out of range
Definitions
• ValueError
• ZeroDivisionError
• KeyError
• IndexError
Exercise 14 — Quiz: Specific vs General Exception Handling
Why is
except ValueError:
better than just
except:
?
Options
• It's more precise and helps with debugging by catching only the expected error
• It makes the program run faster
• It catches more types of errors
• It's required by Python syntax
Hint : Think about what happens if an unexpected error occurs with a general except.
Exercise 15 — Quiz: Use Exception Message
Complete the code to catch the exception and display its error message:
try:
codemon_hp = int("invalid")
except ValueError ____ ____:
print(f"Conversion failed: {e}")
codemon_hp = 100
Options: as e error exception msg message
Hint : Use the syntax that allows you to access the exception object and its message.
Exercise 16 — Quiz: Multiple Exception Handlers
Which except block will execute if
int("abc")
is called?
try:
level = int("abc")
except ValueError:
print("Invalid number")
except TypeError:
print("Wrong type")
except:
print("Other error")
Options
• The ```ValueError``` block
• The ```TypeError``` block
• The general ```except:``` block
• All three blocks
Hint : int() with an invalid string raises ValueError. Python executes only the first matching except block.
Exercise 17 — Quiz: Exception Handling Priority
How many except blocks will execute if an exception occurs?
try:
codemon_hp = int("invalid")
except ValueError:
print("Invalid value")
except TypeError:
print("Wrong type")
except Exception:
print("General error")
Options
• Only ONE - the first matching except block
• All except blocks that match the error type
• Only the most specific except block
• All three except blocks in order
Hint : Python stops checking except blocks as soon as it finds one that matches the exception type.
Exercise 18 — Quiz: Exception Handler Order Matters
What's wrong with this exception handling order?
try:
result = risky_operation()
except:
print("General error")
except ValueError:
print("Value error")
except TypeError:
print("Type error")
Options
• The general ```except:``` catches all errors first, so specific handlers never execute
• You can't have more than two except blocks
• ValueError and TypeError can't be used together
• Nothing is wrong with this order
Hint : Python checks except blocks from top to bottom. What happens when a general except comes first?
Exercise 19 — Quiz: Which Handler Executes?
What will be printed if the dictionary access fails?
codemon = {"name": "Aquachu"}
try:
print(codemon["level"])
except KeyError:
print("Key not found")
except ValueError:
print("Invalid value")
except:
print("Unknown error")
Options
• "Key not found"
• "Invalid value"
• "Unknown error"
• All three messages
Hint : Accessing a non-existent dictionary key raises KeyError. Only one except block executes.
Exercise 20 — Quiz: Match Code to Exception Handler
Match each code operation with the except block that would handle its error:
Items to match
• int("25.5")
• [1, 2][5]
• "level" + 10
• {"hp": 100}["mp"]
Definitions
• except ValueError:
• except IndexError:
• except TypeError:
• except KeyError:
Exercise 21 — Quiz: When else Executes
When does the
else
clause execute in a try/except/else block?
Options
• Only when NO exception occurs in the try block
• Only when an exception is caught by except
• Always, regardless of exceptions
• Before the try block executes
Hint : Think about what makes else special - it's for the success case.
Exercise 22 — Quiz: finally Clause Behavior
What is TRUE about the
finally
clause?
Options
• It ALWAYS executes, whether an exception occurs or not
• It only executes when an exception occurs
• It only executes when NO exception occurs
• It prevents exceptions from being raised
Hint : finally is used for cleanup code that must run no matter what happens.
Exercise 23 — Quiz: Complete try/except/else/finally
Complete the full exception handling structure:
____:
result = 10 / 2
____ ZeroDivisionError:
print("Cannot divide by zero")
____:
print("Success! Result:", result)
____:
print("Cleanup complete")
Options: try except else finally catch always
Hint : Order: risky code, error handling, success code, cleanup code.
Exercise 24 — Quiz: Execution Order with Exception
What is the execution order when an exception OCCURS?
try:
print("A")
x = 1 / 0
except ZeroDivisionError:
print("B")
else:
print("C")
finally:
print("D")
Options
• A, B, D
• A, C, D
• A, B, C, D
• B, D
Hint : When exception occurs: try runs until error, then except, else is skipped, finally always runs.
Exercise 25 — Quiz: Practical else and finally Usage
Complete the code: use
else
for success message and
finally
for cleanup:
codemon_data = {"name": "Aquachu", "level": 50}
try:
power = codemon_data["level"] * 10
except KeyError:
print("Missing data!")
power = 0
____:
print(f"Power calculated: {power}")
____:
print("Calculation complete")
Options: else finally then always success cleanup
Hint : else runs only on success (no exception). finally always runs for cleanup.
Back to the course