简体   繁体   中英

Unity3D Debugger not stepping through method with DebuggerStepThrough Attribute

Unity3D version: 5.6.1f1 Personal.

Summary / TLDR

How do I get the Unity3D debugger to show an exception in the calling function/method?


Details

I'm trying to use a static class/method to make null checks easier. In this static class Ensure I have a static method NotNull with the System.Diagnostics.DebuggerStepThrough attribute on it. This method does the typical null check and exception throwing for me. This attribute is supposed to, as I understand it, make it look like the calling method is throwing the exception. It's not.

The unity debugger still shows the exception being thrown in the static class's method. Does anyone know what I'm missing to get the debugger to work as I described earlier? I've tried this with JMC enabled and disabled.

Static class & method

public static class Ensure
{
    [System.Diagnostics.DebuggerStepThrough]
    public static void NotNull(object valueToTest, string valueName)
    {
        if (valueToTest == null)
            throw new System.NullReferenceException(valueName + " is null");
    }
}


Calling the method

public class foo
{
    public Timer()
    {
        object obj = null;

        Ensure.NotNull(obj, "obj");
    }
}

You're confusing us.

The DebuggerStepThrough Attribute instructs the debugger to step through the code instead of stepping into the code. Its typically used in methods like InitializeComponent() because rarely will you want to step through Design-Time generated code.

I think what you meant to write is the attribute throwing the exception makes it look like the caller method is throwing the exception. That is not right.

Here is the famous QA that discusses it, basically throwing the exception rather than just a throw loses the stacktrace .

Here's a pro tip: Exceptions are supposed to be used exceptionally. They are expensive. Currently you are using Exceptions when you dont need to. The NotNull void would be better as a boolean function:

public static bool IsNotNull(object valueToTest)
{
    return (valueToTest != null);
}

This way if it returns false, you can throw the exception in the caller. That's how you can achieve - what I think it is - you're trying to do.

A better approach altogether is to use the ? null-conditional operator introduced in C# 6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM