c#异常未在异常调试问题的位置停止

huangapple go评论49阅读模式
英文:

c# Exceptions Not Stopping at Location of exception Debugging Problem

问题

抱歉,以下是代码部分,无法提供翻译:

[DoesNotReturn]
private void ThrowSubstringArgumentOutOfRange(int startIndex, int length)
{
    (string paramName, string message) =
        startIndex < 0 ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndex) :
        startIndex > Length ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength) :
        length < 0 ? (nameof(length), SR.ArgumentOutOfRange_NegativeLength) :
        (nameof(length), SR.ArgumentOutOfRange_IndexLength);

    throw new ArgumentOutOfRangeException(paramName, message);
}

private string InternalSubString(int startIndex, int length)
{
    Debug.Assert(startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
    Debug.Assert(length >= 0 && startIndex <= this.Length - length, "length is out of range!");

    string result = FastAllocateString(length);

    Buffer.Memmove(
        elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
        destination: ref result._firstChar,
        source: ref Unsafe.Add(ref _firstChar, (nint)(uint)startIndex /* force zero-extension */));

    return result;
}

希望以上内容对您有所帮助。

英文:

my c# forms app (Vs 2022) in debug mode is just now beginning to show errors in weird places like String.Manipulation.cs. I know the error occurred in my app. But it shows it in some predefined code. I tried to clean and re-open the project, and recompile. But the debug behavior persists. The code below represents a section of the predefined code where it points.

The specific line is

> "throw new ArgumentOutOfRangeException(paramName,message);"

the error details;

> "System.ArgumentOutOfRangeException HResult=0x80131502
> Message=startIndex cannot be larger than length of string. (Parameter
> 'startIndex') Source=System.Private.CoreLib StackTrace: at
> System.String.ThrowSubstringArgumentOutOfRange(Int32 startIndex, Int32
> length) in
> //src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs:line
> 1878 at System.String.Substring(Int32 startIndex) in
> /
/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs:line
> 1837 at cabinetry.frmMain.ProcessScan() in
> C:\Users\doug\source\cabinetry\cabinetry\frmMain.cs:line 487 at
> cabinetry.frmMain.ScannerTime_Tick(Object sender, EventArgs e) in
> C:\Users\doug\source\cabinetry\cabinetry\frmMain.cs:line 558 at
> System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, WM msg, IntPtr
> wparam, IntPtr lparam) at Interop.User32.DispatchMessageW(MSG& msg)
> at
> System.Windows.Forms.Application.ComponentManager.Interop.Mso.IMsoComponentManager.FPushMessageLoop(UIntPtr
> dwComponentID, msoloop uReason, Void* pvLoopData) at
> System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(msoloop
> reason, ApplicationContext context) at
> System.Windows.Forms.Application.ThreadContext.RunMessageLoop(msoloop
> reason, ApplicationContext context) at cabinetry.Program.Main() in
> C:\Users\doug\source\cabinetry\cabinetry\Program.cs:line 14

      [DoesNotReturn]
       private void ThrowSubstringArgumentOutOfRange(int startIndex, int length)
       {
           (string paramName, string message) =
               startIndex &lt; 0 ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndex) :
               startIndex &gt; Length ? (nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength) :
               length &lt; 0 ? (nameof(length), SR.ArgumentOutOfRange_NegativeLength) :
               (nameof(length), SR.ArgumentOutOfRange_IndexLength);

           throw new ArgumentOutOfRangeException(paramName, message);
       }

       private string InternalSubString(int startIndex, int length)
       {
           Debug.Assert(startIndex &gt;= 0 &amp;&amp; startIndex &lt;= this.Length, &quot;StartIndex is out of range!&quot;);
           Debug.Assert(length &gt;= 0 &amp;&amp; startIndex &lt;= this.Length - length, &quot;length is out of range!&quot;);

           string result = FastAllocateString(length);

           Buffer.Memmove(
               elementCount: (uint)result.Length, // derefing Length now allows JIT to prove &#39;result&#39; not null below
               destination: ref result._firstChar,
               source: ref Unsafe.Add(ref _firstChar, (nint)(uint)startIndex /* force zero-extension */));

           return result;



答案1

得分: 0

Form1.cs

namespace WinFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            AddControls();
        }

        private void AddControls()
        {
            // 创建文本框
            TextBox textBox = new TextBox();
            textBox.Location = new Point(50, 50);
            this.Controls.Add(textBox);

            // 创建按钮
            Button button = new Button();
            button.Text = "add input";
            button.Location = new Point(50, 80);
            button.Click += (sender, e) =>
            {
                textBox.Text = "xxx"; // 某些内容

                this.Controls.Add(button);
                int argumentValue = -1;
                int minimumValue = 0;
                int maximumValue = 100;

                if (argumentValue < minimumValue || argumentValue > maximumValue)
                {
                    throw new ArgumentOutOfRangeException("argumentValue", argumentValue,
                        $"参数必须在 {minimumValue} 和 {maximumValue} 之间。");
                }
            };

            this.Controls.Add(button);
        }

        // 其他代码...
    }
}

对于调试并点击所创建的按钮后单步跟踪,会跳转至外部代码(非本人代码)。

正如Alexei提到的,您只需在 "工具" -> "选项" -> "调试" -> "常规" 中选择 "启用仅限我的代码":

顺便提一下,"启用仅限我的代码" 是默认设置,所以下次如果您遇到以前正常但现在变得奇怪的情况,您可以考虑通过以下方式重置整个设置(这样,您无需知道哪个设置引起了问题,只需重置整个设置):

重置环境设置:

关闭特定计算机上的同步设置(此步骤是为了防止设置被覆盖):

c#异常未在异常调试问题的位置停止


<details>
<summary>英文:</summary>

I can reproduce your situation:

**Form1.cs**

    namespace WinFormsApp2
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
    
                AddControls();
            }
        }
    }

**Form1.Designer.cs**

    using System.Windows.Forms;
    
    namespace WinFormsApp2
    {
        partial class Form1
        {
            /// &lt;summary&gt;
            ///  Required designer variable.
            /// &lt;/summary&gt;
            private System.ComponentModel.IContainer components = null;
    
            /// &lt;summary&gt;
            ///  Clean up any resources being used.
            /// &lt;/summary&gt;
            /// &lt;param name=&quot;disposing&quot;&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt;
            protected override void Dispose(bool disposing)
            {
                if (disposing &amp;&amp; (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
            private void AddControls()
            {
                // Create text box
                TextBox textBox = new TextBox();
                textBox.Location = new Point(50, 50);
                this.Controls.Add(textBox);
    
                // create button
                Button button = new Button();
                button.Text = &quot;add input&quot;;
                button.Location = new Point(50, 80);
                button.Click += (sender, e) =&gt;
                {
                    textBox.Text = &quot;xxx&quot;; // something
    
                    this.Controls.Add(button);
                    int argumentValue = -1;
                    int minimumValue = 0;
                    int maximumValue = 100;
    
                    if (argumentValue &lt; minimumValue || argumentValue &gt; maximumValue)
                    {
                        throw new ArgumentOutOfRangeException(&quot;argumentValue&quot;, argumentValue,
                            $&quot;Parameter must between {minimumValue} and {maximumValue}.&quot;);
                    }
                };
    
                this.Controls.Add(button);
            }
            #region Windows Form Designer generated code
    
            /// &lt;summary&gt;
            ///  Required method for Designer support - do not modify
            ///  the contents of this method with the code editor.
            /// &lt;/summary&gt;
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(800, 450);
                this.Text = &quot;Form1&quot;;
            }
    
            #endregion
        }
    }

If I start debugging and click the button I created, click step into, I will jump in the external code(Not my code):

[![enter image description here][1]][1]

# **As Alexei metioned, you just need to select &quot;Enable Just My Code&quot; in Tools -&gt; Options -&gt; Debugging -&gt; General:**

[![enter image description here][2]][2]

[![enter image description here][3]][3]

## **By the way, &quot;Enable Just My Code&quot; is the default settings, so next time if you encounter some situations that something is normal before but become strange now, you can consider to reset the entire settings via these(In the way, you don&#39;t need to know which setting cause the issue, just reset entire settings.):**

Reset environment settings:

[![enter image description here][4]][4]

[![enter image description here][5]][5]

[![enter image description here][6]][6]

[![enter image description here][7]][7]

turn off synchronized settings on a particular computer(This step is to prevent settings override):

![enter image description here][8]][8]

[![enter image description here][9]][9]



  [1]: https://i.stack.imgur.com/9VOOc.png
  [2]: https://i.stack.imgur.com/qwpOc.png
  [3]: https://i.stack.imgur.com/OjUWc.png
  [4]: https://i.stack.imgur.com/zN7tP.png
  [5]: https://i.stack.imgur.com/P56Qk.png
  [6]: https://i.stack.imgur.com/M6yDu.png
  [7]: https://i.stack.imgur.com/DCvEt.png
  [8]: https://i.stack.imgur.com/2AiKm.png
  [9]: https://i.stack.imgur.com/xyFZz.png

</details>



huangapple
  • 本文由 发表于 2023年2月18日 02:38:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75488138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定