哪种更好的设计方法 - 返回bool或抛出异常?

Yul*_*ian 2 c# java exception handle

我想知道哪种方法更好.假设我们有一种方法,例如,发送通知电子邮件.

void SendNotificaitonEmail();
Run Code Online (Sandbox Code Playgroud)

所以,我可以编辑我的SendNotificaitonEmail()方法,所以它现在执行以下操作:

bool SendNotificationEmail(out string errorMessage)
{
    try
    {
        // This is the code that handles the actual sending of the email.
        // ..
    }
    catch(Exception ex)
    {
        errorMessage = ex.Message;
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

但就设计而言,这不是错吗?例如,errorMessage变量与SendNotificationEmail()方法的概念无关.此外,我应该为我的所有方法添加两个新变量 - 布尔值,声明方法的结果(true/false),以及包含错误消息的字符串1(如果有的话).

另一种方法是创建自定义异常并在调用第一个异常的其他方法中处理它们.

public void SendNotificaitonEmail()
{
    try
    {
        // This is the code that handles the actual sending of the email.
        // ..

        if (somethingIsWrong == true)
        {
            throw new MyCustomException();
        }
    }
    catch(Exception ex)
    {
        // Other exception handling code.
        // ..
    }
}

public void OtherMethod()
{
    try
    {
        SendNotificaitonEmail();
    }
    catch(MyCustomException ex)
    {
        // Exception handling code.
        // ..
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 让我们说我想确保在DAL代码中处理的所有操作都能成功执行.

我有一个方法UpdateUserData,GetUserById,ChangeUserPicture.

所以,如果我想检查这些操作是否已成功执行,我应该添加一些额外的变量,如:

bool UpdateUserData(User userToUpdate, out string errorMessage); 
User GetUserById(int id, out bool isError, out string errorMessage);
bool ChangeUserPicture(Picture picture, int id, out string errorMessage);
// ..
Run Code Online (Sandbox Code Playgroud)

我有一个使用所有这些方法的简单应用程序:

string errorMessage;
bool isUserUpdatedSuccessfully = UpdateUserData(someUserToUpdate, out errorMessage); 

if (isUserUpdatedSuccessfully == true)
{
    // If the DAL operation was executed successfully, do something..
}
else
{
    // Code that informs the user that an error has occurred.
    MyCustomErrorLogger(errorMessage);        
}
Run Code Online (Sandbox Code Playgroud)

Mit*_*eat 12

将异常视为异常.不要将它们用于正常的程序流控制.

返回值适用于您期望的事物.

[在本地处理异常而不是返回错误代码的问题在概念上是可以的,但是只有当该代码的所有使用者都检查错误值时,否则会发生错误,然后被忽略.

  • +1就这么简单.不多也不少. (4认同)
  • 很多赞成回答高度自以为是的问题的人 (3认同)
  • 我不认为这是固执己见。据我所知,这是最佳实践。 (2认同)
  • 据我所知,这是固执己见且偏离主题的。 (2认同)