gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:52:25 26 4
gpt4 key购买 nike

在我的代码中,我有一个包含多个 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);
}

}

这是 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()));
}

最佳答案

你做得对(你应该只捕获你要处理的异常,并且没有办法在一个 catch block 中捕获超过一种异常类型),但作为替代,您可以只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;
}
}

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

catch(Exception ex) when (exceptionTypes.Contains(ex.GetType()) {
HandleException(ex);
}

关于C# 如何处理多个相同的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1706556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com