带返回类型的try-catch块 [英] try-catch blocks with the return type
本文介绍了带返回类型的try-catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个返回值的方法,例如
If I have a method that returns something, like
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
}
这会产生编译器错误,显然是因为 catch {}
块不返回任何内容。
This produces compiler error, obviously because catch{}
block does not return anything.
因此,当我有带有返回值的方法时,我不使用try-catch块,这是一个不好的做法。如果有错误,我想将错误字符串设置为该错误。但是然后我也需要一个返回值。忠告?
So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?
推荐答案
将返回值存储在这样的临时变量中:
Store your return value in a temporary variable like this:
public DataTable ReturnSomething()
{
DataTable returnValue = null;
try
{
//logic here
returnValue = ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
return returnValue;
}
这篇关于带返回类型的try-catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文