I realize there are a few questions on best practices for exception handling, but I had to make a few tweaks on the examples I found. My goal was to get rid of basic exceptions like “ArgumentException”, “FileNotFoundException”, “ArrayIndexOutOfBoundsException”, etc.
If you can picture the following code in a hierarchy. So Process() calls ValidateData() which calls CSVData(). I am doing basically this same type of thing, wrapping all of the known functions including my custom ones, then putting that in an exception for the method and passing it up as an inner exception. Is this a decent way to do this task? It works for me, but I want to get in the habit of handling exceptions in a very clean way since some past projects of mine have been covered with “catch(Exception e)….and parse e.Message…”
Here’s my example code:
public class CSVData
{
DataTable data;
public CSVData(string file)
{
try
{
this.data = CSVReader.ToDataTable(file); //throws a few basic exceptions
}
catch (FileNotFoundException e)
{
throw new FailedLoadingCSVException(e, currentLine, file);
}
catch (IOException e)
{
throw new FailedLoadingCSVException(e, currentLine, file);
}
catch (ArgumentNullException e)
{
throw new FailedLoadingCSVException(e, currentLine, file);
}
catch (ArgumentException e)
{
throw new FailedLoadingCSVException(e, currentLine, file);
}
catch (OutOfMemoryException e)
{
throw new FailedLoadingCSVException(e, currentLine, file);
}
}
class FailedLoadingCSVException : Exception
{
public int failedAtLine;
public FailedLoadingCSVException(Exception e, int failedLine, string file)
:base ("The system failed at loading "+file+" at line "+failedLine, e)
{
this.failedAtLine = failedLine;
}
}
}
1 Answer