When used properly (which admittedly is often difficult), exceptions let you write code that isn't riddled with a bunch of error checking. Rather than checking the result of every single operation to see whether or not it failed, you can just write your code assuming it all worked OK, and then write a seperate block of code that's jumped to if there was a problem anywhere along the line.
For example...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// assuming these "DoXXX" functions throw exceptions
try
{
DoSomeStuff();
DoMore();
DoEvenMore();
}
catch(std::exception& e)
{
// something failed somewhere
Cleanup();
AlertUser(e->what());
}
|
This is convenient because:
- all the error code is written once (no duplicate code)
- the error logic is separated from the main logic, making the main logic easier to follow
The common alternative is for functions to return an "error code" to indicate they failed instead of throwing an exception. This causes you do constantly be checking for failures and have error handling code slapped all over the place, making the main logic much more confusing and adding all sorts of duplicate code.
Here's an example of how that might look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
// assuming these "DoXXX" functions return error codes instead of throwing exceptions
int code = DoSomeStuff();
if(code != Success)
{
Cleanup();
AlertUser( GetErrorString( code ) );
return;
}
code = DoMore();
if(code != Success)
{
Cleanup();
AlertUser( GetErrorString( code ) );
return;
}
code = DoEvenMore();
if(code != Succes)
{
Cleanup();
AlertUser( GetErrorString( code ) );
return;
}
|
As you can see this is quite a bit messier.
Does anyone really need an exception to check that the passed variable fits a range? Why? |
If an out of range variable is used as an array index, that could be big problems. Stepping out of bounds in an array is one of the most common ways to get heap corruption, the worst kind of program bug.