+3  A: 

It depends on whether you're actually going to handle the exception, e.g. retry with a slightly different input, or decide to ignore the problem and proceed anyway (rarely appropriate, but can be useful). In this case, you may well want to catch the exception close to its source.

In most cases, the only thing you can really do with an exception is log it and abort the operation (e.g. serve the user an error page in a web app, or pop up a friendly "this program has crashed, sorry" dialog and exit). In this case, your catch block is likely to be quite close to the top of the stack - e.g. in the main method.

Jon Skeet
+3  A: 

The basic rule is that you only catch exceptions in that part of the code, where you can actually handle it. By handling it I mean that you can take some action based upon the exception thrown, for instance trying to create the socket another time, or trying to use a different configuration.

Additionally, exceptions which cross library-boundaries need to be reviewed. Depending on the context you may want to catch them and rethrow a different type of exception, for instance to hide implementation details from the library client.

gimpf
A: 

As for the question about catching the exception in the scope of the function where it's thrown (ie., in the init() function) - it seldom makes sense to catch an exception in the scope where it's thrown. In essence that would mean that you've detected an error and know how to handle it (and are going to handle it), but that you're using an exception to perform nothing more than a transfer of control to another part of your function.

While there might be cases where this might make sense (though that would be a code smell that indicates the function is complex enough that it should be refactored), the logic for handling that error (since it is being handled) should use more common control flow techniques such as if statements or a break. Even the wildly unpopular goto might be preferable to throwing an exception only to have it handled in the same function.

Michael Burr