c# - 如果发生异常,则退出函数/方法

标签 c# asp.net exception

如果子方法中发生异常,我试图找到一个代码来退出整个方法。我尝试在 Subfunction() 的 catch 部分添加返回,但该过程将继续到 Thirdfunction()

 public static void Mainfunction()
    {
        try
        {
            //some code
            //some code
            Subfunction();
            ThirdFunction();

        }
        catch(Exception ex)
        {
            //write to log
        }
    }

    public static void Subfunction()
    {
        try
        {
            //some code
            //some code

        }
        catch (Exception ex)
        {
            //write to log
        }
    }

所以基本上,如果在 Subfunction() 中发生错误,我想从 Mainfunction() 停止进程,而不继续到 ThirdFunction()。任何帮助将不胜感激。谢谢

最佳答案

基本上有两组可能的解决方案:使用异常和不使用异常。

在使用异常的情况下,我建议让它冒泡,正如我在评论中所说的那样。

然后你可以重新抛出:

try {
   // exception here
}
catch(Exception ex)
{
   throw;
   // Attention: this is _different_ from "throw ex" !!
}

注意这里:

You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.

参见 throw (C# Reference) (我强调的)

我自己是从 Java 过来的,这是像我这样的人在从 Java 过渡到 .Net 的过程中会遇到的问题。因此,如果您的团队中有新的“java 人”:不要对他们苛刻,只需让他们查看文档即可。

你可以换行:

try {
   // exception here
}
catch(Exception inner)
{
   throw new MyCustomException( "Some custom message", inner);
}

顺便说一句:捕获异常通常不是一个好主意。大多数时候,您希望捕获您实际可以处理的特定异常。


另一类解决方案是不冒泡异常:

返回值:

public static bool Subfunction()
{
    bool success = true;

    try
    {
        //some code
        //some code

    }
    catch (Exception ex)
    {
        // TODO write error log!
        success = false;
    }
    return success;
}

或返回或错误代码:

// DO NOT USE MAGIC NUMBERS !
private static readonly int SUCCESS_INDICATOR = 0;
private static readonly int ERROR_INDICATOR = 1;

// TODO DOCUMENT which errorcodes can be expected and what they mean!
public static int Subfunction()
{
    int success = SUCCESS_INDICATOR;

    try
    {
        //some code
        //some code

    }
    catch (Exception ex)
    {
        // TODO write error log!
        success = ERROR_INDICATOR;
    }
    return success;
}

尤其是在团队中有“C-Guys”的情况下,您可能会偶然发现这个问题。 (没有冒犯 - 只是我的经验)

或者使用状态对象...

public static void Mainfunction()
{
    try
    {
        //some code
        //some code
        ISuccessIndicator success = new ISIImplementation();
        Subfunction( success );
        if( !succes.HasException ) 
        {
            ThirdFunction();
        }
        else
        {
            // handle exception from Subfunction
        }

    }
    catch(Exception ex)
    {
        //write to log
        //Exceptions from ThrirdFunction or "else" branch are caught here.
    }
}


public static void Subfunction( ISuccessIndicator result )
{
    try
    {
        //some code
        //some code

    }
    catch (Exception ex)
    {
        result.HasException=true;
        result.Exception = ex;
    }
}


public interface ISuccessIndicator 
{
    Exception Exception {get; set;}
    bool HasException {get; set;}
}

如果你真的很疯狂,你可以......

public static void Mainfunction()
{
    try
    {
        //some code
        //some code
        Exception ex = null;
        Subfunction( ref ex );
        if( ex == null ) // or more modern: ( ex is null )
        {
            ThirdFunction();
        }
        else
        {
            // handle exception from Subfunction
        }
    }
    catch(Exception ex)
    {
        //write to log
        //Exceptions from ThirdFunction or "else" branch caught here.
    }
}


public static void Subfunction( ref Exception outEx )
{
    try
    {
        //some code
        //some code

    }
    catch (Exception ex)
    {
        outEx = ex;
    }
}

请注意,我绝不鼓励使用后者。但它是可能的 ...并且 OP 询问了可能性。

免责声明:所有片段均未经测试。谁发现错误可以保留它们(但请写评论,以便我可以修复它们)。

关于c# - 如果发生异常,则退出函数/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223866/

相关文章:

c# - 将泛型方法中的 T 参数转换为 DateTime

c# - 如何在没有 ADO 包装器的情况下在 C# 中使用 SQLite

c# - 有没有办法在不使用端点的情况下从 Identity Server 中生成访问 token ?

asp.net - ASP.NET 中的 Session.Clear() 和 Session.Abandon() 后 session 变量未清除

php - 在 Cakephp 3 : not working 中捕获异常

c# - 如何在 Dynamics CRM 中调用 create 之前删除重复项?

c# - 是否有可能获得一个 Action 中的语句数量或确定它是否有空体?

asp.net - 使用计划任务运行 ASPX 页面时出现问题

java - 找到一个被捕获的异常

language-agnostic - 检查错误的首选方式