And*_*hns 5 c# exception-handling
我在我们的项目中继承了代码,看起来像这样.这是课堂上的一种方法.
protected override bool Load()
{
DataAccess.SomeEntity record;
try
{
record = _repository.Get(t => t.ID.Equals(ID));
if (record == null)
{
throw new InvalidOperationException("failed to initialize the object.");
}
else
{
this.ID = record.ID;
// this.OtherProperty = record.SomeProperty;
// etc
}
}
catch (Exception)
{
throw;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
如果我然后从我的UI层调用这个Load方法,我可能想要一个try catch块来捕获由于加载实例失败导致的任何异常,例如InvalidOperationException,但上面的代码对我来说是错误的.
catch语句不会吞下InvalidOperationException吗?catch语句还将捕获_repository.Get的潜在问题,以及如果记录有效则设置属性的潜在问题.
我想我应该通过添加更多try catch语句来重组它来分别处理Get操作和属性设置操作,或者添加更多catch块来处理不同的异常,但我问了一位同事,他建议try catch与此无关.案件,应该完全删除,留下如下:
protected override bool Load()
{
DataAccess.SomeEntity record;
record = _repository.Get(t => t.ID.Equals(ID));
if (record == null)
{
throw new InvalidOperationException("failed to initialize the object.");
}
else
{
this.ID = record.ID;
// this.OtherProperty = record.SomeProperty;
// etc
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我想要一些第二意见,我刚开始对异常处理感兴趣,所以我想确保按照最佳实践以正确的方式进行.
当你这样做:
catch (Exception)
{
throw;
}
Run Code Online (Sandbox Code Playgroud)
您基本上没有处理异常.然而,这并不意味着你无视它.该throw语句将异常传播到堆栈中.为了清晰可读的代码,你的最后一个例子要好得多.
| 归档时间: |
|
| 查看次数: |
2760 次 |
| 最近记录: |