抛出级联异常

Throw cascaded Exceptions

我想向 GUI 传递多条错误消息。我该怎么做?请看一下我上面的抽象示例:

try
{
    LogIn(usr, pwd); //entry point
}
catch(Exception ex)
{
    throw new Exception("Login failed.");
}



public void LogIn(string usr, string pwd) {

    if(usr == "") {
        throw new Exception("Username was empty.");
    }

    if(pwd== "") {
        throw new Exception("Password was empty.");
    }

    try
    {
        //do some other stuff without a more specific error message
    }
    catch
    {
        throw;
    }  
}

稍后我想得到一个结果错误消息,例如

Login failed. Password was empty.

如果用户没有输入密码。现在我只收到最后一条错误消息 ("login failed."),所以只有我想提供给用户的一半信息。

您可以只使用 ex.Message,即 密码为空。用户名为空。

您可以嵌套 个例外:

try
{
    LogIn(usr, pwd); //entry point
}
catch(Exception ex)
{
    throw new Exception("Login failed.", ex);
}

注意第二个参数,以及 ExceptionInnerException 属性。

但在做之前,请考虑一下上面的块是否添加任何值。如果您只是让 Password was empty 异常转义,调用者通常仍会知道登录失败,并且该异常本身似乎包含所有必需的信息。

如果您有有用的事情,只有catch例外 - 如果您可以恢复错误条件、添加信息或不想公开实现细节你的来电者。否则,让异常上升到可以可以做一些有用的事情的水平。

我会重新考虑你的结构。 正如评论中指出的那样,有一些事情需要考虑:

  • 该方法是否会在别处调用并导致错误使用?
  • 如果我在流程控制中使用异常,是否会导致代码不可读? (Using exceptions for flow control)

List<string> 收集问题的方法:

public void LogIn(string usr, string pwd) 
{   
    List<string> errors = new List<string>();

    if(string.IsNullOrEmpty(usr)) 
    {
        errors.Add("Username is empty.");
    }

    if(string.IsNullOrEmpty(pwd)) 
    {
        errors.Add("Password is empty.");
    }   

    if(errors.Count > 0) // If errors occur, throw exception.
    {
        throw new Exception(string.Join("\r\n",errors));
    }   
}