How can you define catch statement that can catch any type of exception? Illustrate the use of multiple catch statement with example.

This answer is restricted. Please login to view the answer of this question.

Login Now

Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. 

Exception Handling is one of the main advantage of c++.

We will use try and catch block to catch exception. The syntax of try and catch statement is

try {
  // Block of code to try
  throw exception; // Throw an exception when a problem arise
}catch () {
  // Block of code to handle errors
}

We can catch all exception using three dots ... on catch as parameter. The syntax is given below

try {
  // Block of code to try
  throw exception; // Throw an exception when a problem arise
}catch (...) {
  // Block of code to handle errors
}

We can use catch multiple times to catch multiple types of exception. In below example, We have used multiple catch to catch multiple exception.

#include <iostream>
using namespace std;
 
int main()
{
    try  {
       throw 10;
    }
    //catching character exception
    catch (char *c)  {
        cout << "Caught " << c;
    }
    //catching all exception
    catch (...){
        cout << "Exception Occured\n";
    }
    return 0;
}
If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .