I am actually writing a library class which could be used by multiple classes. I am simplying the example so as to make a point. Lets say I have three classes: A, B and C:
public class B
{
public static string B_Method()
{
string bstr = String.Empty;
try
{
//Do Something
}
catch
{
//Do Something
}
return bstr;
}
B is the library class that I am writing. Now there are lets say two other classes say A and C:
public class A
{
public void A_Method()
{
string astr = B.B_Method();
}
}
public class C
{
public void C_Method()
{
string cstr = B.B_Method();
}
}
The question is regarding the exception handling. I want the respective method of the two classes A and B to handle the exception occuring in B_Method in their own different ways.
I looked for framework design pattern, but felt that was not useful.
The approach that I usually follow is this:
The only places where I would put a “catch all” block, is at entry points in UI code (such as event handlers for button clicks and such), since not catching exceptions there might take the process down.
This also means that exception clauses should catch the specific exceptions that you can handle.
One approach that I sometimes see is to catch the exception, wrap it in a new exception type and throw that. While that offers you some traceability, I also feel that it removes some options in the exception handling in calling code, such as having specific catch clauses for different scenarios. In these cases you will instead need to have if-clauses inspecting the inner exception with is less readable in my eyes.