I'm confused about structured error handling. The following piece of
code is a simplification of a class library I'm working on. It works,
and it does what I want, but I'm still not convinced that I have been
doing it right. I think I overdo it. Please have a look:
--
using System;
using System.IO;
namespace ErrorHandlingTest
{
class ErrorHandlingTest
{
[STAThread]
static void Main(string[] args)
{
try
{
Wrapper w = new Wrapper(args[0], args[1]);
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
}
class Wrapper
{
public Wrapper(string file1, string file2)
{
try
{
ReaderType1 reader1 = new ReaderType1(file1);
ReaderType2 reader2 = new ReaderType2(file2);
}
catch (System.Exception e)
{
throw new System.Exception(e.Message);
}
}
}
class ReaderType1
{
public ReaderType1(string file)
{
try
{
StreamReader sr = new StreamReader(file);
}
catch (System.IO.FileNotFoundException e1)
{
throw new System.IO.FileNotFoundException(e1.Message);
}
catch (System.IO.DirectoryNotFoundException e2)
{
throw new System.IO.DirectoryNotFoundException(e2.Message);
}
}
}
class ReaderType2
{
public ReaderType2(string file)
{
try
{
StreamReader sr = new StreamReader(file);
}
catch (System.IO.FileNotFoundException e1)
{
throw new System.IO.FileNotFoundException(e1.Message);
}
catch (System.IO.DirectoryNotFoundException e2)
{
throw new System.IO.DirectoryNotFoundException(e2.Message);
}
}
}
}
--
The part that makes up the class library is the Wrapper and reader
classes. These classes have no direct contact with the user interface,
but there are plenty of things that can go wrong inside them.
After writing and running this, I found that I could remove all error
handling except in Main() and the program ran just as fine (it could
still separate between not finding the folder and not finding the file).
It makes me wonder why I have to write several catch blocks, when all I
need is to catch System.Exception when I use my class library (like in
Main() above).
I want to write robust code, but I fail to see how the code gets *more*
robust by adding error handling inside the class library. It appears as
if classes that shouldn't talk with the user doesn't need error
handling! There must be something I'm missing here.
Gustaf