猿问

如何从遇到错误但需要类型的方法返回

假设我有一个返回 a 的方法,List<int>并且在获取它的过程中List<int>发生错误,因此无法收集数据。在方法中处理此异常的最佳方法是什么?该程序期望该方法返回一个列表,但由于无论出于何种原因发生了错误,它无法再执行此操作。我应该从方法返回什么?是否是调用代码捕获的自定义异常?


private List<int> GetData()

{

  List<in> theData = new List<int>();

  theData = ProcessThatGetsData(); //Error occurs in here

  return theData;  //What should be returned here?

}


翻过高山走不出你
浏览 117回答 2
2回答

一只甜甜圈

如果你想捕获异常并处理它,一种方法是使用像这样的返回对象:&nbsp; &nbsp; &nbsp; &nbsp; private OperationResult GetData()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<int> theData = new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; theData = ProcessThatGetsData(); //Error occurs in here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new OperationResult { Success = true, Data = theData };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; catch (Exception exc)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new OperationResult { Success = false };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return theData;&nbsp; //What should be returned here?&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public class OperationResult&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public bool Success { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public IList<int> Data { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; }这是一个选项,但是我的偏好是不将 try catch 语句放在此处,只放在您真正需要它的层……在这种情况下,您的代码不需要更改或担心返回类型。无论您在何处调用 GetData 方法,都将调用放在 try/catch 语句中,您应该没问题。请记住,始终在必须处理异常的级别处理异常,不要过度处理。

慕桂英546537

是否是调用代码捕获的自定义异常是的,只是让异常发生,调用方法负责处理异常(通过 try-catch 块)。
随时随地看视频慕课网APP
我要回答