Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerException Handling ProgramsExample 1 of 5
basic-try-catch.cpp
1#include <iostream>
2using namespace std;
3
4int divide(int a, int b) {
5 if (b == 0) {
6 throw "Division by zero error!";
7 }
8 return a / b;
9}
10
11int main() {
12 int num1, num2;
13
14 cout << "Enter two numbers: ";
15 cin >> num1 >> num2;
16
17 try {
18 int result = divide(num1, num2);
19 cout << "Result: " << result << endl;
20 } catch (const char* error) {
21 cout << "Error caught: " << error << endl;
22 }
23
24 cout << "Program continues after exception handling." << endl;
25
26 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. 1

    Read two numbers.

  2. 2

    Call divide inside try.

  3. 3

    If b is 0, throw a const char* message.

  4. 4

    catch (const char*) prints it.

  5. 5

    The program continues after the catch.

Dry run: Basic try-catch

Input 10 0

  1. 1.divide(10, 0): b == 0 → throw "Division by zero error!"
  2. 2."Result:" line skipped
  3. 3.catch (const char*) → "Error caught: Division by zero error!"
  4. 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:

Errors or unexpected situations
Thrown when problem occurs
Caught and handled gracefully
Prevents program crashes

Key Components:

try: code that might throw
throw: raises exception
catch: handles exception
Program continues after catch

Throwing Exceptions

Using throw:

if (b == 0) {

throw "Division by zero error!";

}

What happens here:

throw statement raises exception
Can throw any type (string, int, object)
Control immediately jumps to catch
Code after throw not executed

Try Block

Wrapping Code:

try {

int result = divide(num1, num2);

cout << "Result: " << result << endl;

}

What happens here:

Code that might throw goes in try
If exception thrown, jumps to catch
If no exception, continues normally
Can have multiple statements

Catch Block

Handling Exception:

catch (const char* error) {

cout << "Error caught: " << error << endl;

}

What happens here:

Catches specific exception type
Executes when exception thrown
Receives exception value
Program continues after catch

When to Use Exception Handling

Good fits:

Error conditions
Invalid input
Resource failures
Unexpected situations
Robust error handling

Example Scenarios:

Division by zero
File not found
Invalid user input
Network errors
Memory allocation failures

Important Considerations

Exception Types:

Can throw any type
Strings, integers, objects
Standard exception classes
Custom exception classes

Program Flow:

Exception jumps to catch
Code after throw not executed
Program continues after catch
Prevents crashes

Error Messages:

Provide clear error messages
Help with debugging
Inform users of problems
Guide error resolution

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.