I have a method which throws subclasses of Exception. If I am performing the same catch functionality for each sub-class of Exception that\'s causght is it bad practice to just
Yes, it's bad practice, because it makes the catch block catch runtime exceptions that shouldn't be caught.
If you use Java 7, you can use
catch (SomeException | SomeOtherException | YetAnotherException e) {
...
}
If you can do the same functionality for any unexpected execptions (runtime execeptions, for example) thrown by your code, it is fine.
Otherwise, I recommend catching the sub-classes.
Consider what would happen if some part of your code threw a NullPointerException
?
At some point, exceptions have to be handled. So there hopefully is a place in an application that handles (catches) all exceptions. Usually, this is a place where unexpected exceptions are caught to prevent complete application crashes and instead provide some path of recovery, along with some excusing message to the user. In general, in your classes, handle the expected failures and trust the contract your classes and methods provide to the caller. For example, in a method that fetches a record by an ID string from a database, do only catch the SQL exceptions, as your contract may clearly say that a null ID is not allowed. Throw back the bad input exceptions back to the caller, else you may end up validating user input at the wrong level.
Yes it is bad practice to squelch exceptions by catching the Exception class. Exceptions are designed to transmit problem reports to the handler, and doing this could possibly hide a serious error.
It is always suggested to catch possible exceptions (sub classes) than just catching all exceptions using all in one Exception
catch block. Here is one reference.