Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute everything inside catch statement without throwing futher errors

Tags:

c#

I have a piece of code where I try to sign many delegates at once but in case any of them is null I have to unsign all others.

try
{
    this.var1.asdf += ...

    this.var2.asdf += ...

    this.var3.asdf += ...

    this.var4.asdf += ...

    //and so on
}
catch
{
    try {
    this.var1.asdf -= ...
    }catch{}

    try{
    this.var2.asdf -= ...
    }catch{}

    try{
    this.var3.asdf -= ...
    }catch{}

    //and so on
}

How do I avoid all those try catch inside the big catch? I also do not want to use "if not null statements". I want to proceed over all the delegates inside catch block no matter if they might throw null reference exceptions. All lines need to be executed inside catch block.

Is there a way to tell catch to not throw any futher errors and run all its code?

like image 326
dev hedgehog Avatar asked May 07 '26 11:05

dev hedgehog


2 Answers

No there isn't, I normally write a try function if I need to do something and ignore the result. It's not best practise to ignore exceptions, but I understand sometimes it is acceptable to do so:

public T Try(Action<T> action)
{
   try 
   {
      return action();
   }
   catch(Exception ex)
   { 
       // Log the exception so you're at least aware of it
   }
}

You can then call it along the following lines:

Try(() => { var1.asdf.DoSomething(); });

Having read one of your comments, this might be another approach that doesn't use exceptions:

public static void IfNotNull(this T value, Action<T> action)
{
   if(value != null)
      action(value);
}

Then instead you can call, this makes it nice and clean to do the null check in your code and prevents any exceptions (which are quite slow by the way)

var1.IfNotNull(v => v.asdf.DoSomething());
like image 188
Ian Avatar answered May 10 '26 01:05

Ian


Base on @lan response, without anonymous method :

try
{
    this.var1.asdf += var1OnAsdf;

    this.var2.asdf += var2OnAsdf;

    this.var3.asdf += var3OnAsdf;

    this.var4.asdf += var4OnAsdf;

    //and so on
}
catch
{
    TryUnregister(this.var1, var1OnAsdf);
    TryUnregister(this.var2, var2OnAsdf);
    TryUnregister(this.var3, var3OnAsdf);

    //and so on
}

void TryUnregister(VarType var, DelegateType d)
{
    if (var == null) return;
    var.asdf -= d;
}
like image 33
Orace Avatar answered May 10 '26 00:05

Orace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!