There seems to be a difference in viewpoint on how to handle exceptions, so I thought it would be interesting to garner feedback from others on this.
I think it's fair to say that you should handle exceptions at the calling method rather than at the class level but maybe I am wrong. I was also led to believe we should throw exceptions from the class method back to the caller, and then let the caller handle the exception, display error message etc.
Then, I read an article by Anders Hejlsberg, who seemed to offer another method of handling exceptions. He said that one should have 10 try/catch blocks per throw. Since he is the one who created the C# language, it might be good to listen to his advice. I think I read something that throwing exceptions is an expensive operation. I could be wrong and I can't seem to find the article he wrote this in.
So if we follow that advice, should we then turn this class method into this?
And the client handles the exception like this?
I think it's fair to say that you should handle exceptions at the calling method rather than at the class level but maybe I am wrong. I was also led to believe we should throw exceptions from the class method back to the caller, and then let the caller handle the exception, display error message etc.
Then, I read an article by Anders Hejlsberg, who seemed to offer another method of handling exceptions. He said that one should have 10 try/catch blocks per throw. Since he is the one who created the C# language, it might be good to listen to his advice. I think I read something that throwing exceptions is an expensive operation. I could be wrong and I can't seem to find the article he wrote this in.
Code:
public static void updEmployee()
{
try
{
//code for updating an employee in the database
objCmd.ExecuteNonQuery();
}
catch(SQLException ex)
{
throw(ex);
}
catch(Exception ex)
{
throw(ex); }
finally
{
//dispose of objects
}
}
So if we follow that advice, should we then turn this class method into this?
Code:
public static void updEmployee(int empID)
{
//code for updating an employee in the database
objCmd.ExecuteNonQuery();
}
Code:
protected void btn_Click(object sender, EventArgs e)
{
try
{
//code for updating an employee in the database
updEmployee(3333);
}
catch(SQLException ex)
{
lblMessage.Text = ex.Message;
}
catch(Exception ex)
{
lblMessage.Text = ex.Message;
}
finally
{
//dispose of objects
}
}