views:

141

answers:

5

What guidlines do you use when deciding whether to let a method dodge an exception (ie: let the exception propogate up) or handle it once the exception is recieved?

Here is an example of what I am trying to ask

If I have three methods method1,2,3 and 3. Method1 calls Method2 which Calls Method3. and the exception is only thrown in method 3 when should I let the exception propogate upward as follows (excuse my pseudo java ;) )

   method1 {
        try {
            call method2;
        } catch (exception e) {
            doErrorProcessing;
        }
    }

    method2 throws exception {
        call method3;
    }

    method3 throws exception {
        call readFile;
    }

And when should I handle the exception once it is raised as follows

   method1 {
        call method2;
    }

    method2 {
        call method3;
    }

    method3 {
        try {
            call readFille
        } catch (exception e) {
            doErrorProcessing;
        }
    }
A: 

If the lower level routine knows what to do about the exceptional condition, it should probably handle it. If it is an exceptional condition unrelated to the task that function is intended to perform, it would probably make more sense to let it be handled at a higher level.

+1  A: 

Like all answers in software, this one for me is "it depends".

Most exceptions should be, in fact, exceptional, so generally I tend to like them to break the app when they occur. If the exception represents some recoverable error condition, then it should be handled at the point in the call stack when you have the information you need to do so safely. This would include situations where the error can be corrected by the user, i.e. catching the exception to report it back to the user so that they can take appropriate actions.

ckramer
+7  A: 

The rule I follow:

If I can fix an exception, or nullify the problem that caused it (sometimes this means just ignoring it altogether), I'll handle it. Otherwise it gets passed up to the next level.

And I always try to fix exceptions as low in the tree as possible (i.e. as soon as possible after they occur) - this localizes exception handling and avoids big honkin' exception handlers in your upper levels.

paxdiablo
A: 

Only catch exceptions you can handle. Let everything else pass you by.

Brody
A: 

From a Java point of view, I always try and use unchecked exceptions to avoid adding the throws declarations in the method signatures.

Then where I actually catch the exception will be depending on the situation. I'd always want to handle the exception as high in the chain as possible where the exception is applicable. And if it's a system level exception where you expect the application to fall over, then I might have an exception handling mechanism where it will "catch all".

digiarnie