try/catch should be at the level of code that can actually do something about the error.
A common mistake with exception newbies is that they treat exceptions like error codes and put damn near every line in its own try block, which defeats the entire point. The goal is to consolidate the error handling code in one place, so you don't have to be constantly checking to see if your last operation succeeded.
A simplistic example of a good way to use exceptions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// function called when the user presses a button to do something complex
void onButtonPressed()
{
try
{
doComplexOperation();
}
catch(std::exception& e)
{
// report exception message to the user, tell them the operation failed
}
}
void doComplexOperation()
{
doStep1(); // any one of these functions may potentially throw an exception if they fail
doStep2();
doStep3();
doStep4();
}
|
Note that doComplexOperation does not try/catch. This is important because handling the failure is not part of the operation itself (at least not in this case).
Conceptually, if any part of the operation failed (threw an exception), then the operation as a whole should fail (throw an exception).
In that same mindset... the error is handled in the onButtonPressed function because pressing the button didn't fail (therefore it shouldn't throw an exception)... only the operation it performed did.
This allows you to do other things:
1 2 3 4 5 6 7 8 9
|
void onAnotherButtonPressed()
{
try
{
doComplexOperation();
doYetAnotherComplexOperation();
}
catch(...){...}
}
|
If doComplexOperation did the try/catch itself... then flow would continue through to doYetAnotherComplexOperation, even though it shouldn't (since presumably, the 1st complex operation was a prerequisite to completing the 2nd).
The hard part to using exceptions properly is not with the try/catch blocks... but with writing exception-safe code. Exception-safe code has to be aware that an exception could be thrown at any time... and has to be mindful that when that happens, things can be left in a "half completed" state.
EDIT: ninja'd by Catfish.