Basic try-catch in C++
Learn try, catch, and throw in C++ with a division-by-zero example: how throw leaves a function, how catch matches the type, and how the program keeps running.
1#include <iostream>2using namespace std;34int divide(int a, int b) {5 if (b == 0) {6 throw "Division by zero error!";7 }8 return a / b;9}1011int main() {12 int num1, num2;1314 cout << "Enter two numbers: ";15 cin >> num1 >> num2;1617 try {18 int result = divide(num1, num2);19 cout << "Result: " << result << endl;20 } catch (const char* error) {21 cout << "Error caught: " << error << endl;22 }2324 cout << "Program continues after exception handling." << endl;2526 return 0;27}
Sample Output
Error caught: Division by zero error!
The thrown text.
Program continues after exception handling.
Execution resumes after the catch.
In this one
- What throw does to the current function
- How a catch block is chosen by type
- Why the lines after a throw in try are skipped
- Why real code throws std::exception types
How it works
- 1
Read two numbers.
- 2
Call divide inside try.
- 3
If b is 0, throw a const char* message.
- 4
catch (const char*) prints it.
- 5
The program continues after the catch.
Dry run: Basic try-catch
Input 10 0
- 1.divide(10, 0): b == 0 → throw "Division by zero error!"
- 2."Result:" line skipped
- 3.catch (const char*) → "Error caught: Division by zero error!"
- 4.Next line: "Program continues..."
Input 10 0 divide(10, 0): b == 0 → throw "Division by zero error!" "Result:" line skipped catch (const char*) → "Error caught: Division by zero error!" Next line: "Program continues..."
Edge cases
Divisor is not zero
Enter 10 2.
No exception; it prints Result: 5, skips the catch, and continues.
Type mismatch
Change the catch to catch (string error).
A const char* does not match a string catch, so the exception escapes main and the program terminates. Catch types must match closely.
Non-numeric input
Type abc.
cin fails and num1 and num2 become 0, so divide(0, 0) throws the same error.
What's going on
An exception is a way for a function to say "I cannot finish this" and hand the problem to whoever called it. This program uses one to stop a division by zero.
divide checks b == 0 first. Integer division by zero is undefined behavior in C++ and usually crashes the program, so the function refuses to do it and runs throw "Division by zero error!";. The moment throw runs, divide stops. It does not return a value; control jumps out looking for a matching catch.
In main, the call sits inside try { ... }. Because the throw happens, the line that prints "Result:" is skipped. The thrown value is a string literal, whose type is const char*, so catch (const char* error) matches it and prints the message.
After the catch block finishes, the program carries on normally with the line after it, "Program continues after exception handling." That is the whole point: the error was handled and the program did not crash.
With input 10 2, nothing is thrown, the result 5 prints, the catch block is skipped, and the final line still prints.
Throwing a string literal is fine for a first example, but real code throws objects derived from std::exception, such as runtime_error, and catches them by const&. The next programs in this topic do that.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Exception Handling
Exception Concept:
Key Components:
Throwing Exceptions
Using throw:
if (b == 0) {
throw "Division by zero error!";
}
What happens here:
Try Block
Wrapping Code:
try {
int result = divide(num1, num2);
cout << "Result: " << result << endl;
}
What happens here:
Catch Block
Handling Exception:
catch (const char* error) {
cout << "Error caught: " << error << endl;
}
What happens here:
When to Use Exception Handling
Good fits:
Example Scenarios:
Important Considerations
Exception Types:
Program Flow:
Error Messages:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
After throw runs in divide, what happens next?
Pick an answer to check it.
Question 2
Which catch matches throw "oops";?
Pick an answer to check it.
Questions people ask
What happens if nothing catches an exception?
std::terminate is called and the program ends abnormally.
Is a floating-point divide by zero an exception?
No. With doubles it gives inf or nan; nothing is thrown.
Should I use exceptions for every error?
Use them for problems the current function cannot handle. Expected outcomes, like a failed search, are better returned as values.