When should I use a ThrowHelper method instead of throwing directly?

前端 未结 6 1728
傲寒
傲寒 2021-02-05 10:16

When is it appropriate to use a ThrowHelper method instead of throwing directly?

void MyMethod() {
    ...
    //throw new ArgumentNullException(\"param         


        
6条回答
  •  梦毁少年i
    2021-02-05 10:32

    My default approach is to throw directly from the exceptional code branch.

    The DRY principle and the rule of 3 guides when I would wrap that in a method: if I find myself writing the same 'throw' code 3 or more times, I consider wrapping it in a helper method.

    However, instead of a method that throws, it's much better to write a Factory Method that creates the desired Exception and then throw it from the original place:

    public void DoStuff(string stuff)
    {
        // Do something
    
        throw this.CreateException("Boo hiss!");
    }
    
    private MyException CreateException(string message)
    {
        return new MyException(message);
    }
    

    This preserves the stack trace.

提交回复
热议问题