try/except/else/finally, raising and chaining exceptions, and custom exception design.
Question 1: What is exception handling?
Ans
Exception handling lets a program detect and respond to runtime errors using try, except, else, and finally. It keeps error paths separate from normal processing.
Example
python
try:
value = int("abc")
except ValueError:
value = 0
print(value)
Important Point
Catch specific exceptions instead of using a broad `except` that hides unrelated bugs.
Question 2: What is try-except?
Ans
A try block contains code that may raise an exception, while a matching except block handles the exception.
Example
python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Important Point
Only exceptions raised during the protected try block are handled by its except clauses.
Question 3: What is finally?
Ans
finally contains cleanup code that normally runs whether the operation succeeds or an exception is handled.
Example
python
try:
print("work")
finally:
print("cleanup")
Important Point
For files and similar resources, context managers are often cleaner than manual finally cleanup.
Question 4: What is else in exception handling?
Ans
The else block runs when the try block completes without raising an exception.