Skip to main content

Command Palette

Search for a command to run...

Exception Handling in C++ using Try–Catch

Updated
2 min read

Abstract

In C++, runtime errors can cause abnormal program termination. Exception handling provides a structured way to detect and manage such errors. This blog explains the concept of try–catch blocks, throw keyword, types of exceptions, and best practices, with simple examples suitable for NIT / GATE / university exams.


1. Introduction

Errors in a program are broadly classified into:

  • Compile-time errors

  • Run-time errors

  • Logical errors

Run-time errors such as division by zero, invalid memory access, or file handling issues cannot always be detected during compilation.
To handle such errors safely, C++ provides exception handling.


2. What is Exception Handling?

An exception is an abnormal condition that occurs during program execution.
Exception handling allows the program to:

  • Detect the error

  • Transfer control to a handler

  • Continue execution safely

C++ uses three keywords:

  • try

  • throw

  • catch


3. Syntax of Try–Catch

try {
    // code that may generate exception
}
catch (exception_type e) {
    // handling code
}

4. Working Mechanism

  1. Code inside try block is executed.

  2. If an error occurs, throw is executed.

  3. Control jumps to the matching catch block.

  4. Remaining code executes normally.


5. Simple Example: Division by Zero

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 0;

    try {
        if (b == 0)
            throw b;
        cout << a / b;
    }
    catch (int x) {
        cout << "Error: Division by zero";
    }

    return 0;
}

Output

Error: Division by zero

6. Multiple Catch Blocks

Different exceptions can be handled separately.

try {
    throw 3.5;
}
catch (int e) {
    cout << "Integer exception";
}
catch (double e) {
    cout << "Double exception";
}

7. Catch-All Handler

Used when the type of exception is unknown.

try {
    throw 'A';
}
catch (...) {
    cout << "Unknown exception occurred";
}


9. Throwing Exceptions from Functions

void check(int x) {
    if (x < 0)
        throw x;
}

int main() {
    try {
        check(-5);
    }
    catch (int e) {
        cout << "Negative value error";
    }
}