所以我有一个看起来像下面的方法:
private static DataSet GetData()
{
DataSet returnValue = new DataSet();
try
{
//get all relevant tables here, add them to returnValue
}
catch (ArgumentException e)
{
//if a table isn't whitelisted, trying to grab it will throw an ArugmentException.
}
return returnValue;
}
现在,我想传递捕获的异常。但是,例如,如果2个表被列入白名单,而1个未被列入白名单,我仍然希望在DataSet中返回这两个表。我一直在想应该做些类似的事情:
DataSet returnValue = new DataSet();
//TablesToFetch == string list or something containing tablenames you want to fetch
foreach (string tableName in tablesToFetch)
{
try
{
//get table tableName and add it to returnValue
}
catch (ArgumentException e)
{
//handle exception
}
}
return returnValue;
但是,这里的问题是我不能只抛出发现的异常,因为这样一来,就不会返回DataSet。我能想到的第一个解决方案是“捆绑”异常,然后在方法*之外逐个抛出它们,但这让我感到有些混乱。任何人都有如何处理此问题的提示,还是我应该继续执行我刚刚提出的解决方案?
*我可以将方法包装在另一个方法中,该方法在调用GetData()之后将调用“处理所有异常”方法
最佳答案
这很大程度上取决于具体情况...我喜欢这样的方法:
public returnType MyMethod([... parameters ...], out string ErrorMessage){
ErrorMessage=null;
try{
doSomething();
return something;
}
catch(Exception exp){
ErrorMessage=exp.Message;
return null; //
}
}
代替out字符串,您可以创建自己的supi-dupi-ErrorInformation类。您只需调用例程并检查一下,则ErrorMessage为null。如果没有,您可以对输出的值做出反应。也许您只想直接将异常传递出去...
关于c# - 如何在不终止方法的情况下传递异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33300253/