Home
Do you catch exceptions precisely?
  v4.0 Posted at 8/09/2014 10:42 AM by Drew Robson

​​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

We have a program called  SSW Code Auditor to check for this rule.

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.