It's not that you can ONLY do something with exceptions (although Zhuge gave a good example of that), it's that exceptions shorten the error handling process.
Say, for example, you need to do a task that has several steps, each step of which could potentially fail. If any step fails, the whole operation fails.
Without exceptions, to do this you have to check for an error after every step (or sometimes several times in a single step.
Say you want to load an image, modify it, then save it as another file. You could break it into the following steps:
1) Open an image file -- may fail if file doesn't exist
2) Determine its file type (png/gif/jpg/whatever) -- may file is file is not an image, or if it's an unsupported type
3) Load the image -- may fail if file is corrupt or if there's memory errors or whatnot
4) Modify the image
5) Save the image to a new file -- may file if the new file can't be created, run out of space, etc
The error-check method would look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// if all these functions return error codes:
int errcode = OpenFile( file, path );
if( errcode ) return errcode;
int filetype = DetermineFileType( file );
if(filetype < 0) return filetype;
errcode = LoadImage( file, filetype, image );
if( errcode ) return errcode;
errcode = ModifyImage( image );
if( errcode ) return errcode;
errcode = SaveImage( savepath, image, filetype );
if( errcode ) return errcode;
|
As you can see, a lot of repetitive code there. It gets even worse if there are things you have to clean up on failure (like closing the file, freeing buffers, etc)
Exceptions get rid of all that by just letting your throw an exception. That way if an exception isn't thrown, you can assume there is no problem, meaning you never have to check for error conditions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// if all these functions throw exceptions instead of returning error codes:
try
{
OpenFile( file, path );
int filetype = DetermineFileType( file );
LoadImage( file, filetype, image );
ModifyImage( image );
SaveImage( savepath, image, filetype );
return SUCCESS;
}
catch(int errcode)
{
return errcode;
}
|
This code is much simpler, cleaner, and easier to follow. Also note that all of the errors go to the same block of code, so if there's any cleanup that needs to be done when it fails, it can all be done in the same area of code.
Of course using a standard exception is better, because you can give more detailed information about the error. You can include a human readable text string and stuff.