Advertisement



< Prev
Next >



C++ Exception Handling using Try-Catch Block





In our last article, we explained what exactly happens when an exception occurs in a program, how it propagates through a program and eventually ending its execution abruptly. In this article, we are going to explain how to handle an exception thrown in a program, using the try-catch blocks and a throw keyword, so that the program does not have an abrupt end.

A try-catch block is made up of two individual blocks - a try block and a catch block, let's read about these blocks and what are they used for.





Using throw keyword, an exception can be explicitly thrown from within the two places in a program -
As you saw in the last article explaining exception propagation, an uncaught/unhandled exception terminated the program's execution abruptly. In order to not let it happen, we can try to anticipate an occurence of an exception within a program in advance and can use throw keyword to explicitly throw an exception from witin a try block, so that a catch block could catch it and program does not terminate unexpectedly.




How to catch an exception using try-catch block?


Exception thrown has a certain type. In order to catch an exception of a type, we have to make sure that our catch block has declared a type of exception, similar to the type of exception that is thrown by the try block, using throw keyword.


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(int a) //matching int type of exception is declared in "catch block"
{
	cout<<"An exception caught : division by zero \n"; //message related to caught exception is printed
}		

cout<<"Outside try-catch block";
return 0;
} 		


Output :


An exception caught : division by zero
Outside try-catch block


As you can see in the program, it finds a division-by-zero problem and an exception of type int is thrown when a statement enclosed within the try block is executed. This exception is caught by the catch block because it is declared with a matching exception of type int.

As the thrown exception of type int is caught by the catch block, hence, the program does not end abruptly and it continues to successfully execute the statement next to the try-catch block, which prints a message - "Outside try-catch block".




Advertisement




Another example of using try-catch block


Let us see another example in which we are going to catch an out-of-range index exception, which gets thrown when a statement is trying to access an index of array which is out of its range. Let us see how to deal with such exception using try-catch block.

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

using namespace std;

int main() 
{
char arr[5];
try
{
	for (int n=0; n<=6; n++)
    	{
     		 if (n>4) 
			throw std::string("out-of-range");
     		 else 
			arr[n]='a';
    	}
}
catch (std::string st)
{
	std::cout << "Exception caught : " << st;
}
return 0;
}


Output :


Exception caught : out-of-range


As you can see in the program, the compiler finds one of the statements enclosed within the try block is trying to access an invalid-index or out-of-range index hence, an exception of type std:string is thrown This exception is caught by the catch block because it is declared with a matching exception of type std:string.





Mismatch in exception declared and exception thrown





Let us understand this by an example here.
#include<iostream>

using namespace std;

class TryCatch2
{
public: 
void meth();
};



void TryCatch2 :: meth()
{
try
{
	int a = 10;
	int b = 10;

	int result = a-b;
	if(result==0)
	 	throw(b);
	else
	cout<<(100/result);
}
catch(double c) //Non-matching exception-type is declared in this catch block
{
	cout<<"Caught exception type : double type \n";
}
cout<<"Outside try-catch block";
} //meth1() function ends




int main()
{
TryCatch2 ob;
try
{
	ob.meth(); 	//enclosing the call to meth1() function in try block
}
catch(int c)
{
	cout<<"Caught exception : int type \n"	;
}

} //main function ends


Output:


Caught exception : int type

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