c#返回bool或抛出异常的设计方法哪个更好?
我想知道哪种方法更好。比如说,我们有一种方法,可以发送通知电子邮件
void SendNotificaitonEmail();
因此,我可以编辑我的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;
}
}
但就设计而言,这不是不对吗?例如,errorMessage
变量与SendNotificationEmail()
方法的概念无关。此外,我应该在我的所有方法中添加两个新变量——一个是布尔变量,表示方法的结果(真/假),另一个是字符串变量,如果出现错误消息,则包含错误消息
另一种方法是创建自定义异常,并在调用第一个异常的其他方法中处理它们
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.
// ..
}
}
编辑 假设我想确保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);
// ..
我有一个简单的应用程序,它使用了所有这些方法:
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);
}
共 (0) 个答案