Programming Basics
Error Handling (try/catch)
The idea, in plain English
Error handling is a safety net under a tightrope walker. If the walker (your code) slips — say, you try to divide by zero — the net, called `try`/`catch`, catches the fall. The whole show doesn't shut down. Instead of the program crashing, you get a chance to say 'something went wrong, here's what to do instead.'
How it works
- 1Put risky code — code that might fail — inside a `try` block.
- 2If something goes wrong inside `try`, the computer immediately jumps to the matching `catch` block instead of crashing. It hands you details about what went wrong.
- 3A `finally` block, if you add one, runs no matter what happened — whether `try` succeeded or `catch` caught a problem. It's useful for cleanup steps you never want to skip.
When you'd use it
Use error handling anytime something might fail in a way you can predict but not prevent. Examples: reading a file that might not exist, dividing by a number that might be zero, or asking a website for data when the internet might be down.
Common beginner mistakes
- Wrapping your ENTIRE program in one giant `try`. This hides exactly where something went wrong. Keep `try` blocks small and focused.
- Catching an error and then doing nothing with it (an empty `catch`). This silently hides bugs instead of fixing or reporting them.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Attempted: 10 / 2
Result: 5.00
Attempted: 10 / 0
Error: Cannot divide by zeroNot sure this is the right topic? See the learning paths → or where this leads →