Skip to main content

Posts

Showing posts with the label Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it properly.

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