C# 向调用者抛出异常

Ric*_*ves 0 c# exception throws

我有一个需要抛出异常的函数,但我希望它将该异常抛出到我调用该函数的行:

static int retrieveInt()
{
    int a = getInt();
    if(a == -1)
        throw new Exception("Number not found"); //The runtime error is pointing to this line
    return a;
}

static void Main(string[] args)
{
     int a = retrieveInt(); //The runtime error would be happening here
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ves 5

经过两个小时的搜索,我找到了问题的答案。要执行我想要的操作,需要在函数之前使用 [System.Diagnostics.DebuggerStepThrough]:

[System.Diagnostics.DebuggerStepThrough]
static int retrieveInt()
{
    int a = getInt();
    if(a == -1)
        throw new Exception("Number not found"); //The runtime error will not be here
    return a;
}

static void Main(string[] args)
{
     int a = retrieveInt(); //The runtime error happens now here
}
Run Code Online (Sandbox Code Playgroud)