- 01Getting Started
- 02Your First Output (cout)
- 03Variables and Types (int/double/string/bool)
- 04Conditionals (if statements)
- 05Loops (for statements)
- 06Writing a Function
- 07Working with Arrays
- 08Loops (while statements)
- 09Pointer Basics
- 10References
- 11Classes (Object-Oriented Programming)
- 12Constructors and Destructors
- 13Inheritance
- 14Using vector (the Standard Library)
- 15String Manipulation (string)
- 16Structs (struct)
- 17Error Handling (try/catch)
- 18The Ternary Operator
- 19The switch Statement
- 20[Applied] Build a Mini Inventory Management System
Error Handling (try/catch)
This lesson covers try/catch, used to handle an abnormal situation (an exception) that occurs at runtime. It's for anyone searching "C++ exception handling try catch."
Write logic that might fail inside try { ... }, and throw an exception with throw. It's caught with catch (type variableName) { ... }, where you handle the error case.
The example throws a std::runtime_error when trying to divide by zero, and displays the error message inside catch.
A common early mistake is overusing exceptions. Trying to handle every single error with an exception makes a program's flow hard to follow, so it's generally considered good practice to reserve them for genuinely "exceptional" situations.
In real projects, exception handling is used for abnormal situations that are awkward to handle with a plain if statement โ a missing file, memory that couldn't be allocated, and so on.
๐งช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
