Exception Handling in Python
Exceptions are errors while the program is running. 10/0, int("Asha"), open a missing file. If you don’t handle them, the script dies with a traceback. try/except lets you print a clear message and continue — or stop cleanly.
Shape: try: risky lines. except ZeroDivisionError: handle. finally: cleanup. Don’t write bare except: — it hides bugs. Catch the type you expect. else on try runs only if no error. finally almost always runs (close file).
Let’s dry-run. try: print(10/0) except ZeroDivisionError: print("Cannot divide by zero"). Output: Cannot divide by zero. The print(10/0) never finishes. That is the example, not a dummy pass.
raise ValueError("amount must be > 0") when your own function gets bad input. Caller can except it. Interview: try/except/finally + one real error name.
Exception Handling in Python — output — Cannot divide by zero. 10/0 throws; except prints the message.
try: 10 / 0
│ ZeroDivisionError
▼
except → Cannot divide
│
▼
finallyWalk through try/except/finally with a file or divide example.