C#如何处理完全相同的多个异常?

Mar*_*ijn 6 .net c# asp.net exception

在我的代码中,我有一个带有多个catch语句的方法,它们执行所有相同的语句.我不确定这是实现这个的正确方法.你会怎么做?

public void LoadControl(ControlDestination controlDestination, string filename, object parameter)
{
    try
    {
        // Get filename with extension
        string file = GetControlFileName(filename);

        // Check file exists
        if (!File.Exists(file))
            throw new FileNotFoundException();

        // Load control from file
        Control control = LoadControl(filename);

        // Check control extends BaseForm
        if (control is BaseForm)
        {
            // Set current application on user control
            ((BaseForm)control).CurrentApplication = this;
            ((BaseForm)control).Parameter = parameter;

            // Set web user control id
            control.ID = filename;

            Panel currentPanel = null;

            switch (controlDestination)
            {
                case ControlDestination.Base:
                    // Set current panel to Base Content
                    currentPanel = pnlBaseContent;
                    // Set control in viewstate
                    this.BaseControl = filename;
                    break;
                case ControlDestination.Menu:
                    // Set current panel to Menu Content
                    currentPanel = pnlMenuContent;
                    // Set control in ViewState
                    this.MenuBaseControl = filename;
                    break;
            }

            currentPanel.Controls.Clear();
            currentPanel.Controls.Add(control);
            UpdateMenuBasePanel();
            UpdateBasePanel();

        }
        else
        {
            throw new IncorrectInheritanceException();
        }
    }
    catch (FileNotFoundException e)
    {
        HandleException(e);
    }
    catch (ArgumentNullException e)
    {
        HandleException(e);
    }
    catch (HttpException e)
    {
        HandleException(e);
    }
    catch (IncorrectInheritanceException e)
    {
        HandleException(e);
    }

}
Run Code Online (Sandbox Code Playgroud)

这就是HandleException的样子:

private void HandleException(Exception exception)
{
    // Load error control which shows big red cross
    LoadControl(ControlDestination.Menu, "~/Controls/Error.ascx", null);

    // Store error in database
    DHS.Core.DhsLogDatabase.WriteError(exception.ToString());

    // Show error in errorbox on master
    Master.ShowAjaxError(this, new CommandEventArgs("ajaxError", exception.ToString()));
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*man 12

你做得对(你应该只捕获你将要处理的异常,并且无法在一个catch块中捕获多个异常类型),但作为替代方案,你可以只catch(Exception ex)检查异常类型,如果它不是你想要的throw那个,那样的话:

var exceptionTypes=new Type[] {
    typeof(FileNotFoundException),
    typeof(ArgumentNullException),
    //...add other types here
};

catch(Exception ex) {
    if(exceptionTypes.Contains(ex.GetType()) {
        HandleException(ex);
    } else {
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:使用C#6(与Visual Studio 2015一起使用),您可以执行以下操作:

catch(Exception ex) when (exceptionTypes.Contains(ex.GetType()) {
    HandleException(ex);
}
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用`exceptionTypes.Any(type => type.IsAssignableFrom(ex))`而不是简单的相等比较. (5认同)
  • 它应该是exceptionTypes.Any(type => type.IsAssignableFrom(ex.getType())) (2认同)