Advertisement



< Prev
Next >



C++ Multiple Catch Blocks





So far, we have only seen one catch block associated with a try block. But it is also possible to have multiple catch blocks associated with one try block.




Why multiply blocks are useful?


Multiple catch blocks are used when we have to catch a specific type of exception out of many possible type of exceptions i.e. an exception of type char or int or short or long etc. Let's see the use of multiple catch blocks with an example.




Multiple Catch Block Example


#include<iostream>

using namespace std;

int main()
{
int a=10, b=0, c;
try
{
	//if a is divided by b(which has a value 0);
	if(b==0)
		throw(c); 
	else
	c=a/b; 		
		
}
catch(char c)     //catch block to handle/catch exception
{
	cout<<"Caught exception : char type ";
}
catch(int i)     //catch block to handle/catch exception
{
	cout<<"Caught exception : int type ";
}
catch(short s)     //catch block to handle/catch exception
{
	cout<<"Caught exception : short type ";
}
cout<<"\n Hello";
}


Output is -:


Caught exception : int type
 Hello

In this code, we have three catch blocks associated with one try block. At the runtime, compiler finds a division-by-zero problem, hence an exception of type int is thrown when a statement enclosed within the try block is executed.

This exception type is matched with the declared exception type in every catch-block(matching starts with the first catch block).


The catch block that matches with type of exception thrown is executed, while the rest of catch blocks are skipped. Let's see how -


Advertisement




A catch block for all types exceptions


We could declare a catch block which catches all types of exceptions, irrespective of their types. In such catch block, instead of declaring the type of exception it can catch, we are going to use three dots(...) within its parenthesis. Let's see an example.

Let's understand this by an example -
#include<iostream>

using namespace std;

int main()
{
int a=10, b=0, c;
try
{
	//if a is divided by b(which has a value 0);
	if(b==0)
		throw(c); 
	else
	c=a/b; 		
		
}
catch(...)     //catch block to handle/catch exception
{
	cout<<"A catch block for all types of exceptions has caught an exception";
}

}


Output


A catch block for all types of exceptions has caught an exception


Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement

/