Closing the application when unhandled exception occurs (C#)

Godot Version

v4.7.2.stable.mono.official [ed1daf0bf]

Question

Default behavior of .NET application is that it closes when exception is thrown and not caught, to prevent application from staying in corrupted state and potentially even corrupting data.

Default Godot 4 behavior is opposite - it doesn’t care about unhandled exceptions, and keeps executing what code it still can. While it shows errors in the editor, you have no idea anything wrong happens in release version of the game. Apparently Godot 3 was working the same as default .NET application.

I’ve seen issues on GitHub dating back as far as 3 years where people request old behavior being added back, but as far as I know it still hasn’t been added. I couldn’t find any toggle in the settings either.

So here is my question - what is the best approach to deal with it? One way is to add try-catch that closes application in every entry point (_Ready, _Process, event handlers, etc), but that’s a lot of extra work. Possible, but not the most feasible. I have also found this:

public static void setupExceptionHandler()
    {
        AppDomain.CurrentDomain.FirstChanceException += unhandledException;
    }

    private static void unhandledException(object sender, FirstChanceExceptionEventArgs e)
    {
    }

I haven’t tested it yet, it apparently does work and will catch every exception, but also those that were caught and handled, which is not optimal behavior.

I don’t want to sound entitled, because this is free and open source engine, and you can make real games with it, but it’s massive pain point, and I want to know if clean solution exists.

Godot is written in C which has no try/catch

The C programming language does not have built-in try-catch exception handling. Instead, catching errors in C relies on defensive programming, checking function return values, and monitoring the global errno variable.

So how did they manage to make it work in Godot 3? I don’t think they have rewritten Godot in C in 4th version.

I think I’ve found solution to this problem, which I will share, but I genuinely want to know why it worked in 3 but not in 4, so I don’t want to make this comment contain too much information at once.

If you just want to capture unhandled exceptions change
AppDomain.CurrentDomain.FirstChanceException
to
AppDomain.CurrentDomain.UnhandledException

See Unhandled exception Event for more information.

I don’t think this will necessarily work if there’s an internal Godot exception that got triggered by your C# code. Since that’s technically not a .NET exception.

This is actually something I’m interested in as well since it somewhat affects me as well from time to time.

My main solution though is the fact that I do very defensive programming, which usually prevents this, but it’s obviously a lot of extra work.

I believe you are correct. Any exceptions occurring in managed code, or in the interop layer should bubble up to provide a true c# exception.

It’s my understanding though that for errors at the engine level that Godot pushes the error to the debugger console, and attempts to safely fail out or continue executing, potentially in an unhandled, invalid state.

In Godot 3 there was a GD.UnhandledException to catch these things, and was configurable via project settings, but it is not present in 4.

I have done some more digging and found out about _LogError from Logger. It fires when an unhandled exception occurs, and perhaps in other error-related situations. The catch is that it doesn’t work in debug mode, but works in release mode, so it’s not obvious at first that it does indeed work.

An example:

public partial class CrashLogger : Logger
{
    private bool _crashed;

    public override void _LogError(
        string function, string file, int line, string code, string rationale,
        bool editorNotify, int errorType, Godot.Collections.Array<ScriptBacktrace> scriptBacktraces)
    {
        if (_crashed)
            return;

        _crashed = true;

        Callable.From(() =>
        {
            OS.Alert($"Fatal error.");
            ((SceneTree)Engine.GetMainLoop()).Quit(1);
        }).CallDeferred();
    }
}

And apparently it also needs to be registered in autoload or any other node that exists at all times:

_logger = new CrashLogger();
OS.AddLogger(_logger);

In this example I’m terminating the game while showing a popup, but I’m positive you can do variety of other things, like going to different game menu with more elegant error message, or trying to recover, etc.