尝试 - 赶上回归策略

use*_*186 5 c# asp.net

try-catch在方法中使用时,如果您希望应用程序即使出现错误也能继续,是否可以通过catch块返回默认值作为return,并记录错误以供日后查看?

例如:

public static string GetNameById(int id)
{
    string name;
    try
    {
        //Connect to Db and get name - some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        name = String.Empty;
    }

    return name;
}
Run Code Online (Sandbox Code Playgroud)

例2:

public static string GetIdByName(string name)
{
    int id;
    try
    {
        //Connect to Db and get id- some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        id = 0;
    }

    return id;
}
Run Code Online (Sandbox Code Playgroud)

是否可以返回任何默认值(取决于方法的返回类型...... ???),以便需要此方法的结果的应用程序逻辑不会崩溃并继续...

提前致谢...

问候.

Nei*_*ell 6

对异常处理的建议是,大多数情况下,您应该只捕获可以执行某些操作的异常(例如,重试操作,尝试不同的方法,提升安全性等).如果您在应用程序的其他位置记录全局级别,则不需要这种catch-log-return.

个人 - 通常 - 在这种情况下我会这样做:

public static string GetNameById(int id)
{
    string name;
    try
    {
        //Connect to Db and get name - some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        throw; // Re-throw the exception, don't throw a new one...
    }

    return name;
}
Run Code Online (Sandbox Code Playgroud)

像往常一样 - 这取决于.

但要注意其他陷阱,例如调用方法没有意识到存在失败,并继续执行工作,假设抛出异常的方法实际上有效.此时,您将开始关于"返回代码与抛出异常"的对话,您可以在SO.com和一般的互联网上找到大量资源.


Liv*_* M. 0

最好记录异常,然后重新发送它,以便上层可以正确处理它。

注意:“记录异常部分”当然是可选的,并且在很大程度上取决于您的处理策略(您会在其他地方再次记录它吗?)

与其通过吞噬异常来使应用程序不崩溃,不如让它们通过并尝试找到它们首先被抛出的根本原因。