Is there any mechanism in C # for a custom method of a custom class that will force you to use this method in external code only in a try-catch block?

  • 6
    not. checked exceptions in java is not here. and this is good. For the calling code knows best when and what it should intercept. - vitidev
  • "for a custom method of a custom class" - give an example. - Igor
  • 3
    @vitidev is worth posting as an answer - PashaPash
  • @Igor public class Division {public decimal Calculate (decimal a, decimal b) {return a / b;}} - maratsoft
  • @maratsoft - What are you changing conditions on the go? So virtual is this a method or not? - Igor

2 answers 2

In c #, there is no equivalent of java checked exceptions, so the method cannot require using try / catch at the place where this method is called.

The calling code itself decides at which level it should try.catch and cannot be controlled from the nested code.

    public abstract class BinaryOperation { protected abstract decimal DoCalculate(decimal a, decimal b); public decimal Calculate(decimal a, decimal b) { try { return DoCalculate(a, b); } catch(...) { ... } return 0; } public abstract string Name { get; } } public class Division : BinaryOperation { protected override decimal DoCalculate(decimal a, decimal b) { return a / b; } public override string Name { get { return "Деление"; } } } 
    • And who minus, what is wrong then? Quite a correct way to wrap potentially dangerous sections of code redefined in the heirs. - Monk
    • @Monk put a plus, but the wrong thing here is that this is not the answer. Here the caller himself decided to wrap the callee in the try..catch (or may not), but according to the logic of the ts, the callee should force the try..catch to be used - vitidev
    • @vitidev the unsafe call problem it solves. - Monk