views:

55

answers:

2

I have a base class, and I would like to catch all exceptions of the derived class within the base class, is this possible?

You won't know what the methods are from the derived class.

+1  A: 

You need to provide more details about your specific scenario. However if for example you have a base abstract class that provides a contract and you want to catch all possible exceptions thrown by derived classes when calling the base class contract you can do something like this:

public abstract class Base
{
    protected abstract void InternalFoo();
    protected abstract void InternalBar();

    public void Foo()
    {
        try { this.InternalFoo(); }
        catch { /* ... */ }
    }

    public void Bar()
    {
        try { this.InternalBar(); }
        catch { /* ... */ }
    }
}
João Angelo
Yes this is a possible way, can you do this without using an abstract class, as I will not know what the methods are from the derived class
Coppermill
@Coppermill, this approach is only feasible if the methods for which you want to catch exceptions are defined in the contract of the base class. This approach will not work for methods that the base class has no knowledge about.
João Angelo
+1  A: 

By calling class you mean a derived class, or a non-related class calling methods from a class derived from your base?

I guess you can do that turning your base into a proxy class. See a dynamic proxy example.

jweyrich