0

I have the following situation:

class A
{        
    abstract void foo()
    {
    }
}

many MANY classes inherit from A, and override foo().

I want to catch all exceptions thrown from those overridden foos.

I thought about decorating A's foo, and to try..catch all of foo's contents, and was hoping the overriding classes' foos would also be decorated with the try..catch from the base A's foo.

Is this doable? If so, how? Is there a better way?

Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • 1
    You can have a look at possible ways in this [thread](https://stackoverflow.com/questions/24457988/can-we-catch-exception-from-child-class-method-in-base-class-in-c) – Pavel Anikhouski Nov 03 '19 at 17:13
  • Why do you want to do that? Most of the time I favor composition over inheritance. For example: Have your "many" classes be consumed by another class that can take care of handling the exceptions properly. Maybe an interface will do... – Dennis Kuypers Nov 03 '19 at 19:29

1 Answers1

1

You can use this:

public class A
{        

    public void Foo()
    {
      try
      {
        DoFoo();
      }
      catch
      {
      }
    }

    protected abstract void DoFoo();

}

Hence you will write:

public class B : A
{        

    protected override void DoFoo()
    {
    }

}
  • all classes overriding `foo` will not have access to DoFoo, and will not run the code you suggested. I am trying not to change their code. This solution breaks them. – Gulzar Nov 03 '19 at 17:15
  • So there is no way, as I know. You ask to modify unmodifiable code, If I understand... It may be impossible. –  Nov 03 '19 at 17:16
  • I want only A to change, not all of its derived classes and client's code. – Gulzar Nov 03 '19 at 17:18
  • 1
    I was basically thinking about @OlivierRogier's suggestion as well, and I'm pretty sure he's right - there's no solution that does what you want and does not involve changes in the inheriting classes. Think about it, in you're current implementation, the execution never enters any code inside `A`, so no change you do in `A` will affect anything. – Nimrod Dolev Nov 03 '19 at 17:18
  • @Gulzar One thing you can perhaps do, if you have control on the code, is first to rename foo in dofoo using visual studio rename tool, next you add the suggested foo. So from external classes that call foo nothing is changed...Client's code see no changes... That's *refactoring*. You should change the new public dofoo as protected to be scrupulous, it is the hard part you say you don't want to do, because VS has not this tool yet, but it is not required and you can let the accessibility level as is. So you can do the job in few seconds. –  Nov 03 '19 at 17:28