Lets say you have a function that normally returns an integer, but on occasion needs to return a string. This is a case where you could use an exception. The exception being the return of a string.
#include <iostream>
using namespace std;
int UnknownMethod(int Num)
{
if (Num == 2000000)
throw "Two million";
if (Num % 2 == 1)
return Num + 1;
else
return Num;
}
int main(void)
{
long total = 0;
for (int x = 0; x < 2000020; x++) {
try
{
total += UnknownMethod(x);
}
catch(char const *ExNum)
{
cout << "String with value: " << ExNum << endl;
}
}
cout << "The total is " << total << endl;
return 0;
}
And this works as long as printing the string is an exception. Let's say that a programmer sees this code and decides to implement it in a situation where integers and strings are equally likely. In this case the code might look like:
#include <iostream>
using namespace std;
void UnknownMethod(int Num)
{
if (Num == 2000000)
throw "Two million";
if (Num % 2 == 1)
throw Num + 1;
else
throw Num;
}
int main(void)
{
long total = 0;
for (int x = 0; x < 2000020; x++) {
try
{
UnknownMethod(x);
}
catch(int ExNum)
{
total += ExNum;
}
catch(char const *ExNum)
{
cout << "String with value: " << ExNum << endl;
}
}
cout << "The total is " << total << endl;
return 0;
}
This code is completely wrong. The correct code being:
#include <iostream>
using namespace std;
union data {
char const *string;
int number;
};
int
UnknownMethod (int Num, union data * ret)
{
if (Num == 200000)
{
ret->string = "Two million";
return 1;
}
if (Num % 2 == 1)
ret->number = Num + 1;
else
ret->number = Num;
return 0;
}
int
main (void)
{
long total = 0;
union data dat;
for (int x = 0; x < 2000020; x++)
{
if (UnknownMethod (x, &dat))
{
cout << "String with value: " << dat.string << endl;
}
else
{
total += dat.number;
}
}
cout << "The total is " << total << endl;
return 0;
}
The difference in speed is striking between the exception base code and the union based code. On my computer the union based code runs in 44 milliseconds. Where the exception based code takes 9 seconds.
This example is extreme and contrived, but it is important to be sure that your exceptions are exceptions and don't become bottle necks.