25 Nov 2019

  • November 25, 2019
  • Amitraj
Catch All Exceptions in C++

-> In some situations, we may not be able to anticipate types of exceptions and therefore may not be able to design independent catch handlers to catch them. In such circumstances, we can force a catch statement to catch all exceptions instead of a certain type alone. This could be achieved by defining the catch statement using ellipses as follows:



  catch (. . .) 
  {
                  // statement for processing
                  // all exceptions
                ...
   }

   // illustrates the functioning of catch(. . .)


// C++ program to catching all exceptions.

#include<iostream>
using namespace std;
void test(int x)
{
try
{
if(x==0) throw x;     // int
if(x==-1) throw 'x';  // char
if(x==1) throw 1.0;   // float
}
catch(...)
{
cout<<"Caught an exception \n";
}
}

int main()
{
cout<<"Testing Generic catch \n";
test(-1);
test(0);
test(1);
return 0;

}

OUTPUT:

Testing Generic catch
Caught an exception
Caught an exception

Caught an exception

Related Posts:

  • C++ Classes and Objects Class:- -> Language supports different data type like int, float, char, long, structure etc. Similar to that C++ supports class data type. -> A class is a user defined data type which has data members and member funct… Read More
  • Class Scope (C++ only) Class Scope in C++ -> A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function's class. -> When the scope of a declaration extends t… Read More
  • Constant Member functions in C++ Constant Member functions in C++ -> A constant (const) member function can be declared by using const keyword, it is used when we want a function that should not be used to change the value of the data members i.e. any … Read More
  • Static Data Member in C++ Static Data Member in C++ -> A data member of a class can be qualified as static .The properties of a static member variable are similar to that of C static variable. 1. It is initialized to zero when the first object … Read More
  • Copy Constructor in C++ Copy Constructor in C++ A copy constructor is a member function which initializes an object using another object of the same  class. A copy constructor has the following general function prototype:     &nbs… Read More

Translate

Popular Posts