Why is it better not to catch exceptions in general classes?

When you implement a class for some general purpose, why is it better not to catch exceptions?

I assume that the error can go up the stack and help in the debugging process. Any other reasons?

+3
source share
4 answers

This rule is best read: Do not handle Exceptions that you do not know how to handle it!

If, for example, you write a class that reads a CSV file and returns line markers, you will have several points in your class where an IOException may be thrown. You definitely will not catch him, because it is not your responsibility to handle this! Your task is to convert the byte stream to the token stream, nothing more. If someone sends you a corrupt stream, this should be handled by him, not by you.

EDIT . One more example. If your library, for example, reaches a SocketException and the socket was passed to lib from the caller, then throw a SocketException. If your library is an abstract connection structure that can also connect to files, memory, etc., and SocketExceptions are not shared, wrap them in ConnectionException.

+10

- .

" Java":

, , , . , . , API . , , , , . , , , .

+2

, - , . , , IOException -. .

"", , . , , .

+1

!

Exceptions should only be caught where they make sense and can be handled. The idea is to propagate the exception to the application level to the point where either the user or the business logic MAY take some action regarding the exception.

+1
source

All Articles