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')?