This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Friday, March 17, 2023

Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it properly.

 Here is an example program that demonstrates the use of try and catch block to handle an exception:

#include <iostream>
#include <string>
using namespace std;

void divide(int a, int b) {
    if (b == 0) {
        throw "Divide by zero exception";
    }
    cout << "a/b = " << a/b << endl;
}

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;

    try {
        divide(a, b);
    }
    catch (const char* msg) {
        cerr << "Exception caught: " << msg << endl;
    }
    return 0;
}

In this program, we define a function divide that takes two integers as arguments and throws an exception if the second argument is zero. The main function reads two integers from the user and calls the divide function within a try block. If an exception is thrown, the catch block catches the exception and prints an error message.

Sample Output:

Enter two numbers: 10 0
Exception caught: Divide by zero exception

In this case, the user tried to divide 10 by 0, which is not allowed, so the program threw an exception and the catch block caught it and displayed the error message.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget