0

Assume you have one object that has two methods which both throw different exceptions. These methods must be used together. For instance:

SqlCon{
  static SqlCon connect(string user, string pass) throws UnableToConnect;
  string[] query(string query) throws BadQueryExcep;
}

Options 1.

try{
   SqlCon s = connect("user", "pass");
   s.query("myquery");

}catch(UnableToConnect e || BadQueryExcep b){
  //do something with error
}

Option 2.

 try{
       SqlCon s = connect("user", "pass");
       try{
         s.query("myquery");
       }catch(BadQueryExcep b){
        //do something with different error
       }


    }catch(UnableToConnect u){
      //do something with error
    }

Option 3.

SqlCon s;

try{
   s = connect("user", "pass");


}catch(UnableToConnect e){
  //do something with error
  return;
}
try{
   s.query("myquery");
}catch(BadQueryExcep b){
  //do something with different error
}

Options 4.

try{
   SqlCon s = connect("user", "pass");
   s.query("myquery");

}catch(UnableToConnect e){
  //do something with e
}catch(BadQueryExcep b){
 //do something with b
}

Option 4 seems the cleanest to me but if there were a lot of statements within the try{..} block, you would be hiding where the exception occurred.

Which option would you choose and why? Which option would you not choose and why? Is there better options available (operating within the constraints of the question...don't just say 'You should throw the exception')?

1

Option 1 or 4. The others add a lot of visual confusion without improving the behavior in any way.

Assuming these exceptions have reasonably descriptive error messages (eg, "Could not connect to database", "Syntax error in query after 'SELECT' token", etc) which you can access via the usual e.what(), then Option 1 is probably the best because you'll likely use the exact same code to handle both types of exceptions. If for some reason you need to handle the two exception types differently, then Option 4 is better.

Note that "hiding where the exception occurred" is not an issue at all as long as the error messages are reasonably descriptive (and if they aren't, that's the first problem to tackle). Especially in the context of databases, the error message probably tells you far more than which line of code threw it.

In addition to the readability problem, with Options 2 and 3 the first/inner try-catch block is probably using exceptions as control flow, which we all know is an anti-pattern for plenty of other reasons.

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.