Exception Handling in C++

Exceptions are errors which occur during the runtime of a program. With Exception Handling in C++, you are able to handle runtime errors in a structured and controlled way. C++ exception handling system is built upon three keywords:

  • Try
  • Catch
  • Throw

The try keyword must have a portion of your code that you want to monitor for errors. The throw keyword will then pass the value to the exception handler, known as the catch statement, which will then processes the exception. If an exception is thrown for where there is no catch statement applicable, the program will stop abruptly in an uncontrolled manner, hence you will need to catch all exceptions that will be thrown in your code.

Below is a code example of all the three keywords of exceptions being put into practice:

</pre>
<pre>// Exceptions code sample

include <iostream>

using namespace std;

void Exception_test(int test)
{
cout << "Inside Exception test: " << test << "\n";
if(test)
{
// This exception is caught by the catch statement in main()
throw test;
}
}

int main()
{
cout << "Start the program";

// Start a try block
try
{
cout << "Inside the try block\n";
Exception_test(0);
Exception_test(1);
Exception_test(2);
}

// Catch an error
catch(int i)
{
cout << "Caught an exception, the value is: ";
cout << i << "\n";
}

cout << "end of the program";

return 0;
}</pre>
<pre>

Catching All Exceptions

In certain situations, you will want an exception handler to catch all exceptions instead of a certain type. The follow code example applies this:

</pre>
<pre>// Catching all exceptions example

#include <iostream>
using namespace std;

void Handle_test(int test)
{
try
{
if(test == 0)
// Throw int
throw test;
if(test == 1)
// Throw char
throw 'i';
if(test == 2)
// Throw double
throw 150.55;
}

catch(...)
{
// Catch all the exceptions
cout << "Got one of them\n";
}
}

int main()
{
cout << "Start the program\n";

Handle_test(0);
Handle_test(1);
Handle_test(2);

cout << "End the program";

return 0;
}</pre>
<pre>

Specifying Excepetions thrown by a function

You can also specify the type of exception that a function can throw outside of itself

</pre>
<pre>// Specifing Exceptions thrown
#include <iostream>
using namespace std;

//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
// The function can only throw ints, chars and doubles
//−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
void Handle_test(int test) throw(int, char, double)
{
if(test == 0)
// Throw int
throw test;
if(test == 1)
// Throw char
throw 'i';
if(test == 2)
// Throw double
throw 150.55;
}

int main()
{
cout << "Start the program\n";

try
{
// Try passing 1 and 2 to Handle_test()
Handle_test(0);
}

catch(int i)
{
cout << "Caught int\n";
}

catch(char c)
{
cout << "Caught char\n";
}

catch(double d)
{
cout << "Caught double\n";
}

cout << "End the program";

return 0;
}</pre>
<pre>
Share this post