What is the purpose of `try...except` in Python?
B
To handle exceptions and prevent program crash
C
To test for syntax errors
D
To comment out code blocks
Analysis & Theory
`try...except` is used to catch and handle exceptions during runtime, preventing program crashes.
What will this code print?
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Analysis & Theory
The exception is caught, and the message is printed instead of crashing the program.
Which of the following is the correct syntax?
A
try: x = 10 except: pass
B
try x = 10 except: pass
C
try: x = 10
except:
pass
Analysis & Theory
`try` must be followed by a colon and indented block, then `except:` with its own block.
Which keyword can be used to execute code regardless of exception?
Analysis & Theory
`finally` is executed no matter what — whether an exception occurred or not.
What is the output?
try:
print(x)
except NameError:
print("x is not defined")
Analysis & Theory
`x` is undefined, so it raises `NameError` and the message is printed.
Which block will execute if no exception is raised?
Analysis & Theory
If no exception occurs, the `else` block (if present) will execute.
What will happen if no `except` block is provided and an error occurs?
D
It automatically retries
Analysis & Theory
If there's no `except` block and an exception is raised, the program crashes.
Which block always runs, whether or not an exception occurs?
Analysis & Theory
`finally` always runs after `try...except`, regardless of exceptions.
What does this do?
try:
1 / 0
except:
print("Error")
finally:
print("Done")
Analysis & Theory
The `except` catches the error, and `finally` runs afterward.
How can you catch multiple exception types in one `except` block?
A
Separate them with `or`
B
Use multiple `except` statements
C
Use a tuple: `except (TypeError, ValueError):`
Analysis & Theory
Multiple exceptions can be caught in one block using a tuple.