jeudi 29 janvier 2015

Exception handling scope when dealing with nested exceptions


Assume you have one object that has two function calls which both throw different exceptions. These functions must be executed close to simultaneously. 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
}


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





Aucun commentaire:

Enregistrer un commentaire