2

Why can't I make a class for a Try including what I try and then run that in the try {} block? Why is it impractical?

class DBConnectTry extends Try {    
  TryResponse response[] attempt(TryObject o[]...){
     //try to connect to database
  }    
}

Then in a try ... catch I could invoke only the DBConnectTry.attempt. Would that improve readability / clarity / modularization or is it not a good idea?

  • 8
    This seems to stem from the common fallacy that you want to be catching exceptions often. Catching exceptions is actually a pretty rare case, because you only want to do it at the stage you can do something meaningful to recover. A huge chunk of issues you just can't recover from, so at best they should be caught at your top level which logs/alerts and then either ignores or quits depending on whether it's left your application in an invalid state or not. – Phoshi May 1 '14 at 8:20
  • I'm having trouble figuring out exactly what your classes represent. Could you elaborate, please? – JvR May 19 '14 at 17:52
1

I would say this is not a good idea. This kind of encapsulation is not a standard practice for exceptions, because exceptions should be... exceptionally rare to begin with. Code of this variety looks good on paper, but in practice it will be a nightmare to maintain. Write only enough code to get the problem solved. See the KISS principle, and don't repeat yourself.

Redundant code does not help code clarity, or readability, and adding extra classes and methods for small tasks will only make your application source bloat.

Also, consider that it will be more difficult to remove such classes later (if need arises) than it is to implement them in the first place.

Consider using the throws keyword to propagate exceptions to a calling class, and then handle them there. Instead of an interface Try, with implementing class DBConnectTry, create a method in your impl database connection class that has one try catch block for each connection.

public class DBConnectionManager{
    public Connection getConnection() throws SQLException {
        Connection conn = null;
        conn = //Get connection obj from DriverManager or whatever
        return conn;
    }
}

Every call to DBConnectionManager#getConnection should handle SQLExceptions, or pass them up to the next calling class.

Also, look into logging frameworks like log4j and slf4j. You do not need a class to encapsulate Exception messages (your TryResponse class). You can bin multiple messages into simple arrays/lists of String objects.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.