Advertisement



< Prev
Next >



C++ Throw Keyword





In C++, you may use throw keyword when you explicitly want to throw an exception. The keyword throw is followed by a variable of a primitive data-type or an object of a type that you want to throw. Using throw keyword, an exception can be explicitly thrown from within the two places in a program -




throw in try block



double d = 10.3;
try
{
throw d;       // An exception of type int is caught by this catch block and the same type of exception is thrown.
}





throw in catch block


To throw an exception out of a catch block, keyword throw is followed by a certain type of variable that was already caught by this catch block or a different type of exception. For example -



catch(int i)
{
double d = 10.2;
throw d;       // An exception of type int is caught by this catch block but an exception of type double is thrown.
}



Advertisement




Using throw keyword to throw an exception out of try block


#include<iostream>

using namespace std;

int main()
{
char c = 'c';
try
{
	throw(c);   // "throw", explicitly throws an exception object of any type 
}
catch(char c)
{
	cout<<"Thrown Exception : char type ";
}
}


Output is -:


Thrown Exception : char type

As you can see in the code above, an exception object of type char is explicitly thrown using the keyword throw. This exception is then caught in the catch block which is declared with a matching exception-type, i.e. char. In the output, we have printed a message, that displays the type of exception caught in catch block.





Using throw keyword, to throw an exception caught in the catch block


#include<iostream>

using namespace std;

int main()
{
try
{
	throw(1); //throws an exception of type int
}
catch(int i)
{
	cout<<"Exception caught - int type \n";
	cout<<"Caught exception is thrown again \n";
	throw i; //throwning the caught exception of type int
}

}


Output -


Exception caught - int type
Caught exception is thrown again
terminate called after throwing an instance of 'int'

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.






Please share this article -





< Prev
Next >
< Multiple Catch Blocks
C++ Console I/O Functions >



Advertisement

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

PYTHON


Advertisement