ITP

IMCA - Object Oriented Programming C++

Explain use of try, catch and throw blocks in exception handling in c++

In : IMCA Subject : Object Oriented Programming C++

In C++, exception handling is used to handle runtime errors so that the program can continue running or terminate gracefully. The three keywords used are: 

  • try: This block contains code that might cause an error .
  • throw: Used inside the try block to throw an exception when an error occurs.
  • catch: This block catches and handles the exception thrown by throw.

Example :

#include
using namespace std;

int main() {
    try {
        int age;
        cout << "Enter your age: ";
        cin >> age;

        if (age < 0) {
            throw age; // Throw an exception if age is negative
        }

        cout << "You are " << age << " years old." << endl;
    }
    catch (int e) {
        cout << "Error: Age cannot be negative (" << e << ")" << endl;
    }

    return 0;
}

About us

A truly open platform where you may ask questions and get answers. We also provide comprehensive and easy-to-understand answers to question papers.  discover...

Site status

Flag Counter

Privacy Policy

Sitemap