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

Exception handling uses try-catch blocks. Code that might throw exceptions goes in try block. catch block handles exceptions. throw statement throws an exception. If exception is thrown, control jumps to catch block. Program continues after catch block. This prevents program crashes and allows graceful error handling.

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.

Table of Contents