Concepts 🚀 Project 🧮 Labs
🧮 Labs / Python / try / except / finally

try / except / finally

Errors are raised, caught, handled. Don't swallow exceptions silently — at least log them.

script.py v3.1
Python output click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
🧠 How it works

try: runs code that might fail. except: catches specific exception types. else: runs only if NO exception was raised (rare but useful). finally: ALWAYS runs, even on exception — use for cleanup (closing files, releasing locks). Catch SPECIFIC exceptions (except ValueError), not bare except: (catches everything including KeyboardInterrupt). raise ValueError('message') throws an exception. raise by itself re-raises the current one. Common exceptions: ValueError, TypeError, KeyError, IndexError, FileNotFoundError, AttributeError. You can create custom exceptions: class MyError(Exception): pass.

✏️ Try these changes
  • Change divide(10, 0) to divide(10, 5)
    → no ZeroDivisionError
  • Remove the 'as e' from except ZeroDivisionError:
    → still works but you can't print the message
  • Add except Exception: print('unknown error') at the end
    → catches any other exception
  • Change raise ValueError to raise RuntimeError
    → different exception type caught (or not)