Is the following method of exception handling correct? I am finding it difficult to log the error and finally send the log file through email.
Where do I write code to log the error and send email?
A major problem I get is that when the exception is generated in SomeClass1 it is logged two times – the second time from SomeClass2. Is it a good idea to create a single custom exception type (SomeException in the example) and wrap the System.Exception whenever it occurs?
Also I am confused about how and when to show error message to the end user when we have a chain of try-catches calling one another.
class SomeClass1
{
public static DataExtract(string sourcepath)
{
try
{
OleDbConnection oledb = new OleDbConnection();
oledb.ConnectionString = "someconnectionstring";
CompanyOLEDB.Open();
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
class SomeClass2
{
private void SomeMethod()
{
try
{
// some code
// some code
SomeClass1.DataExtract()
}
catch (Exception e)
{
throw new CustomException(e);
}
}
}
public class CustomException : Exception
{
protected CustomException() { }
public CustomException(Exception e)
{
Log(e);
}
public CustomException(ExceptionType type)
{
this.Data.Add("Type", type);
this.Data.Add("Message", "No message specified");
}
public CustomException(ExceptionType type, string message)
{
this.Data.Add("Type", type);
this.Data.Add("Message", message);
}
public static void Log(Exception e)
{
System.IO.File.WriteAllText(Logfile.txt", e.ToString());
}
public static void Sendmail()
{
ExceptionMail.Sendmail();
}
}
No. There are several issues. Here is the two most important ones.
1. You should not catch exceptions that you can’t handle
Quite important. All exception blocks that just rethrow or log exceptions clutter the code without adding any value. Only catch all exceptions in the topmost layer (in the webservice, the MVC controller, in a background thread etc) to prevent the application from crashing. (however, it’s sometimes better to let the application crash).
An exception have been handled if the method can return the expected value.
2. Always include the original exception
You are hiding information that is important to be able to prevent the information in the future when you only copy partial information from the original exception.
If you must catch/throw other you should do it like this:
// and in a method:
Changes compared to your code:
operation specificmessage, i.e. describing what we tried to do when the exception happened (instead of using the original message)More information
I’ve written several blog posts about exception handling.
You can start by reading: http://blog.gauffin.org/2010/11/do-not-catch-that-exception/
And than read the rest: http://blog.gauffin.org/tag/exceptions/