Basic try-catch

Basic try-catch Block in C++

BeginnerTopic: Exception Handling Programs
Back

C++ Basic try-catch Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero error!";
    }
    return a / b;
}

int main() {
    int num1, num2;
    
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    
    try {
        int result = divide(num1, num2);
        cout << "Result: " << result << endl;
    } catch (const char* error) {
        cout << "Error caught: " << error << endl;
    }
    
    cout << "Program continues after exception handling." << endl;
    
    return 0;
}
Output
Enter two numbers: 10 0
Error caught: Division by zero error!
Program continues after exception handling.

Understanding Basic try-catch

This program teaches you how to use Basic try-catch Blocks in C++. Exception handling allows programs to gracefully handle errors and unexpected situations without crashing. The try-catch mechanism is essential for robust, production-quality code.

---

1. What This Program Does

The program demonstrates basic exception handling:

Throwing exceptions using throw statement
Catching exceptions using try-catch blocks
Handling division by zero error
Continuing program execution after exception

Exception handling prevents crashes and enables graceful error management.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.

---

3. 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

---

4. Throwing Exceptions

Using throw

:

if (b == 0) {

throw "Division by zero error!";

}

How it works

:

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

---

5. Try Block

Wrapping Code

:

try {

int result = divide(num1, num2);

}

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

How it works

:

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

---

6. Catch Block

Handling Exception

:

catch (const char* error) {

}

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

How it works

:

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

---

7. When to Use Exception Handling

Best For

:

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

---

8. 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

---

9. return 0;

This ends the program successfully.

---

Summary

Exception handling: use try-catch blocks to handle errors gracefully.
throw: raises exception when error occurs.
catch: handles exception, receives exception value.
Program continues after catch block, prevents crashes.
Understanding exception handling enables robust error management.
Essential for production-quality code and graceful error handling.

This program is fundamental for learning error handling, understanding exception mechanisms, and preparing for robust program development in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Basic try-catch

This C++ program is part of the "Exception Handling Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents