从布尔方法捕获异常消息

本文关键字:消息 捕获异常 方法 布尔 | 更新日期: 2023-09-27 18:05:36

我见过类似的问题,但不完全是这样:

我想知道确定方法是否正确执行的正确方法,返回一个布尔值,如果方法没有执行,知道原因,即使抛出异常。

我这样做,但我认为return内捕获是一个不好的做法,所以哪一个是正确的方式?:

if(!myObject.DoSomething('A', out result))
{
    MessageBox.Show(myObject.ErrorMessage);
    [...]
}else{
    MessageBox.Show(result);
    [...]
}
class myObject()
{
    public string ErrorMessage;
    bool DoSomething(char inputValue, out string result)
    {
        try
        {
            if(inputValue == 'A')
            {
                ErrorMessage = "Bad input value: " + inputValue;
                return false;
            }
            [...]
            return true;
        }catch(Exception ex){
            ErrorMessage = ex.Message;
            return false;
        }
    }

我不喜欢在catch中显示异常,因为我失去了对应用程序的控制(并且我无法获得描述),并且异常总是在表单中结束。如果我在表单中显示异常,我就不需要在其他类中使用try catch。

我的意思是try {} catch(Exception ex) { throw ex;}和不放try catch是一样的。

thanks a lot

从布尔方法捕获异常消息

我的建议是创建您自己的Exception类型(可能是全局的),并将其作为引用传递。

之后,你仍然可以返回指示成功或失败的布尔值(并且在try..catch之外只有一个返回)。

 public class CustomException
 {
    private string _message;
    private string _title;
    public CustomException()
    {
      _title = "";
      _message = "";
    }
    public CustomException(string title, string message)
    {
      _title = title;
      _message = message;
    }
 }

然后调用DoSomething,传入一个CustomException实例(在本例中是ce)。

CustomException ce = new CustomException();

请注意,这是解决必须返回指示成功或失败的布尔值并知道消息的问题的最佳过程,例如;将其转储到日志文件或记录到数据库(特别是对于服务调用- WCF)

Return false内部捕获本身并不是不好的做法。当你处理一段代码的异常时,它是有用的,并且它不能失败。

例如,我当时正在处理一个打印机引导DLL,这个DLL必须读取包含多条记录的XML文件才能打印。该方法不能因为一条记录打印失败而失败,但是如果XML文件格式不正确,它仍然可以返回异常。

public void Print(string xmlFile)
{
    if (String.IsNullOrWhiteSpace(xmlFile))
        throw new ArgumentNullException("No xml file has been passed to the Print method.");
    // This line will most likely throw an exception if the XMl file is not well formated
    XDocument dom = XDocument.Load(xmlFile);
    foreach (XElement n in dom.XPathSelectElements("//RECORDS/RECORD"))
    {
        try
        {
            // send commands to the printer, if the printer fails to print, throw a PrinterRecordException
        }
        catch (PrinterRecordException e)
        {
            // log print failure, but keep on printing the rest
            continue;
        }
        catch (Exception e)
        {
            // dunno what happened, but still have to print the rest
            continue;
        }
    }
}

在这个例子中,我的函数可以返回false而不是向主程序抛出异常,如果主程序不在乎的话。在我看来,你应该这样考虑你的方法。

异常处理方法和最佳实践是一个有点主观的问题。我不能证明我将要介绍的方法,因为我才刚刚开始在我自己的项目中使用它。

我建议有一个静态的ExceptionHandler类,你可以用它注册任何异常,由通用参数及其相应的处理程序处理。如果你想在发生特定异常时显示某种消息框,这将使你的业务逻辑与你的UI分离。

下面是一个例子:

/// the real implementation uses lambda's and/or implementations of IExceptionHandler<TException>
ExceptionHandler.Register<InvalidPasswordException>(() => /*some handler logic*/);
// ... else where in the code ...
catch (InvalidPasswordException ex)
{
    // do resource clean-up and raise exception for listeners such as the UI or logging infrastructure.
    ExceptionHandler.Raise(ex);
}

到目前为止,这看起来很有希望,特别是与我以前的方法相比。但只有时间才能证明。

ExceptionHandler类本身不需要是静态的,例如,如果您正在使用分层体系结构,您可能希望在应用程序的不同层有不同的ExceptionHandler实例。