Reputation: 181
When you implement a class for some general-purpose use, why is it best not to catch exceptions?
I suppose it's so that the error can go up the stack and help in the debugging process. Any other reasons?
Upvotes: 3
Views: 611
Reputation: 28074
This rule should better read: Do not handle Exceptions you do not know how to handle!
If e.g. you write a class that reads a CSV file and return the tokens of the line, you will have some points in your class where an IOException might be thrown. You should definitely not catch it, because it is just not your responsibility to handle it! Your task is to convert a stream of bytes into a stream of tokens, nothing more. If someone passes a corrupt stream to you, this should be handled by him, not you.
EDIT: Another example: If your library for example reaches a SocketException, and the socket has been given to the lib from the caller, then pass the SocketException up. If your library is just an abstract connection framework, that could also connect to files, memory etc., and SocketExceptions are not common, wrap them in a ConnectionException.
Upvotes: 10
Reputation: 3215
The exceptions should be caught only where are meaningful and can be treated. The idea is to propagate the exception up to the application's layers to a point where either the user or the business logic CAN take some action regarding the exception.
Upvotes: 1
Reputation: 61011
Its ok to catch exceptions if you have something useful to do after catching them. For instance, suppose you get an IOException
after attempting to make a web service call. Under certain circumstances, it might make sense to catch that exception and retry the call.
Catching exceptions becomes a "bad thing" when you swallow them without handling them appropriately. In that case you are better off throwing the exception, and handling it from a higher level where its more clear what the behavior should be.
Upvotes: 1
Reputation: 10580
It is more object-oriented and hide implementation details.
As said Joshua Bloch in Effective Java:
It is disconcerting when a method throws an exception that has no apparent connection to the task that it performs. This often happens when a method propagates an exception thrown by a lower-level abstraction. Not only is this disconcerting, but it pollutes the API of the higher layer with implementation details. If the implementation of the higher layer changes in a subsequent release, the exceptions that it throws will change too, potentially breaking existing client programs. To avoid this problem, higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction.
Upvotes: 2