Rules

Secret ingredients to quality software

Edit
Info

Do you catch exceptions precisely?

Last updated by Brady Stroud [SSW] on 17 Mar 2021 05:43 am (about 2 months ago) See History

In the try and catch block, if you always catch for normal Exception you will never know where the true problem is. When using try you should always expect some exception may happen, so in our code we always catch the specific exceptions.

try 
{ 
     connection.Open();
}
catch (Exception ex) 
{ 
     return ex.ToString ();
}

Bad code – Catching the general Exception

try 
{ 
     connection.Open(); 
}
catch (InvalidOperationException ex) 
{ 
     return ex.ToString(); 
}
catch (SqlException ex) 
{ 
     return ex.ToString(); 
}

Good code - Catch with specific Exception

Adam CoganAdam Cogan
Drew RobsonDrew Robson

We open source. This page is on GitHub