C # Action is interrupted if an Exception occurs in the middle

1 minute read

It’s different from what I thought!

When I was using C #’s ʻAction as a callback listener, there was a behavior like" I thought it was different! ", So I verified it again. I'm running on .NET 4.x in Unity, but I think the same thing will happen on any platform with C # .

Test code

Test code


//Listener for callback
public event Action OnSomething;

private void Start()
{
    //Register each callback
    OnSomething += OnSomething1;
    OnSomething += OnSomething2;
    OnSomething += OnSomething3;

    //Run event
    OnSomething?.Invoke();
}

private void OnSomething1()
{
    Debug.Log("1");
}

private void OnSomething2()
{
    throw new NotImplementedException();
}

private void OnSomething3()
{
    Debug.Log("3");
}

When I run this code, it looks like this:

log


1
NotImplementedException: The method or operation is not implemented.

Originally, OnSomething1 to 3 are independent, so I would like 3 to be executed even if ʻException` occurs in 2, but it is not output.

If you do try-catch like this, 3 will also be executed.

try-catch


private void OnSomething2()
{
    try
    {
        throw new NotImplementedException();
    }
    catch (Exception e)
    {
        Debug.LogException(e);
    }
}

log


1
NotImplementedException: The method or operation is not implemented.
3

What are you scared of

I think that it is a rather common usage to say “I will publish the callback, so anyone can register for the event as they like!”, But with this behavior, “Someone who registered elsewhere throw Then the event will not come to me ** (and I can’t even know it) ** “, which is quite scary.

In addition, ʻAction of C # `cannot be canceled by registering an event with a lambda expression, and there are many other” kowa ~ “behaviors. It would be better if I was told that it would be better than it used to be.

Anyway, the good boy is the event subscriber, so let’s use Reactive Extension or ʻUniRx` which can keep and destroy the state of subscribing to the event as an instance! It was a story called [^ reactive].

That’s it.