c# – 异常没有陷入catch块

前端之家收集整理的这篇文章主要介绍了c# – 异常没有陷入catch块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个try,catch和finally块的函数.如果捕获到异常,那么我会捕获该异常的某些参数,例如其错误代码,错误详细消息和消息,并将其打印在excel文件中.我发布以下相关代码
  1. public void UpdateGroup(String strSiteID,String strGroup,int row)
  2. {
  3. try
  4. {
  5. Console.WriteLine("UpdateGroup");
  6. Excel1.MWMClient.MWMServiceProxy.Group group = new Excel1.MWMClient.MWMServiceProxy.Group();
  7. group.name = "plumber";
  8. group.description = "he is a plumber";
  9. Console.WriteLine(groupClient.UpdateGroup(strSiteID,group));
  10. ExcelRecorder(0,null,row);
  11. }
  12. catch (System.ServiceModel.FaultException<DefaultFaultContract> ex)
  13. {
  14. ExcelRecorder(ex.Detail.ErrorCode,ex.Detail.Message,ex.Message,row);
  15. }
  16. finally
  17. {
  18. System.GC.Collect();
  19. }
  20. }
  21.  
  22.  
  23.  
  24. public void ExcelRecorder(int error,string detailmessage,string message,int row)
  25. {
  26. Excel.Application xlApp = new Excel.Application();
  27. Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/WebServiceTestCases_Output.xlsx");
  28. Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
  29. Excel.Range xlRange = xlWorksheet.UsedRange;
  30. if (!string.IsNullOrEmpty(message))
  31. {
  32. ((Range)xlWorksheet.Cells[row,"M"]).Value2 = "FAIL";
  33. ((Range)xlWorksheet.Cells[row,"N"]).Value2 = error;
  34. ((Range)xlWorksheet.Cells[row,"O"]).Value2 = detailmessage;
  35. ((Range)xlWorksheet.Cells[row,"P"]).Value2 = message;
  36. }
  37. else
  38. {
  39. ((Range)xlWorksheet.Cells[row,"M"]).Value2 = "PASS";
  40. ((Range)xlWorksheet.Cells[row,"N"]).Value2 = "";
  41. ((Range)xlWorksheet.Cells[row,"O"]).Value2 = "";
  42. ((Range)xlWorksheet.Cells[row,"P"]).Value2 = "";
  43. }
  44. xlWorkbook.Save();
  45. xlWorkbook.Close(0,0);
  46. xlApp.Quit();
  47. }

问题是,早些时候我有一段代码就像

  1. catch(Exception ex)
  2. {
  3. ExcelRecorder(ex.Message);
  4. }

那时,所有例外都被抓住了.但是,后来需求发生了变化,因为我还需要捕获错误详细信息代码错误详细信息.所以,我用catch(System.ServiceModel.FaultException ex)改变了我的catch块,因为它允许我获取那些参数.但是现在,某些例外情况并没有被捕获.如何更改我的catch块以便能够捕获所有异常?

解决方法

基本上有两种方式:

1:两个捕获块(最具体的第一个):

  1. catch (System.ServiceModel.FaultException<DefaultFaultContract> ex)
  2. {
  3. ExcelRecorder(ex.Detail.ErrorCode,row);
  4. }
  5. catch (Exception ex)
  6. {
  7. // TODO: simpler error handler
  8. }

2:一个带有测试的catch块:

  1. catch (Exception ex)
  2. {
  3. var fault = ex as System.ServiceModel.FaultException<DefaultFaultContract>;
  4. if(fault != null)
  5. {
  6. ExcelRecorder(fault.Detail.ErrorCode,fault.Detail.Message,fault.Message,row);
  7. }
  8. // TODO: common error handling steps
  9. }

要么可以工作.第一个可能更干净,但是如果你想在捕获物内部做很多常见的事情,第二个可能有优势.

猜你在找的C#相关文章