C# 带有返回类型的 try-catch 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/602699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try-catch blocks with the return type
提问by
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;
}
}
This produces compiler error, obviously because catch{}
block does not return anything.
这会产生编译器错误,显然是因为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?
所以当我有返回值的方法时,我不使用 try-catch 块,这是一个不好的做法。如果有错误,我想将错误字符串设置为该错误。但是我也需要一个返回值。建议?
采纳答案by Simon
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;
}
回答by Manrico Corazzi
You should raise/throw the exception in your catch block and handle it in the calling method.
您应该在 catch 块中引发/抛出异常并在调用方法中处理它。
public void invokeFaultyCode()
{
try
{
DataTable dt = ReturnSomething();
}
catch(Exception e)
{
// Print the error message, cleanup, whatever
}
}
public DataTable ReturnSomething() throws Exception
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw;
}
}
PS: Sorry for any syntax error, I'm a bit rusty on C#.
PS:抱歉有任何语法错误,我对 C# 有点生疏。
回答by Anton Gogolev
It depends on you application. You can return null
, an empty DataTable
or whatever is suitable under circumstances.
这取决于您的应用程序。您可以 return null
,空的DataTable
或任何适合情况的东西。
回答by Bryan Sebastian
You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.
你应该用 try catch 包裹调用者......在被调用的例程中发生的任何异常都会冒泡给调用者,你可以在那里捕获它们。
Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.
就个人而言,我认为在此例程中使用 try catch 是过度的,因为您应该让调用方处理异常。
For my example, this would be coded as follows...
对于我的例子,这将被编码如下......
private void DoSomething() {
try {
DataTable dt = ReturnSomething();
}
catch (Exception ex) {
}
}
public DataTable ReturnSomething() {
DataTable dt = new DataTable();
// logic here
return dt;
}
回答by Mehrdad Afshari
I think your code is being run at a sufficiently high level of the call stack and it's blended with UI code. If this is really the case, you could return null
in the catch block. However, if you are writing reusable code, you should refactor it so that it doesn't contain UI manipulation and handle the exception at a higher level in the call stack.
我认为您的代码在调用堆栈的足够高的级别上运行,并且它与 UI 代码混合在一起。如果确实如此,您可以return null
在 catch 块中。但是,如果您正在编写可重用的代码,则应重构它,使其不包含 UI 操作并在调用堆栈中的更高级别处理异常。
回答by Kris
Since you are cacthing the exception (and not throwing it again) in your example, The outside code assumes everyting is okay and therefor you should return something useful.
由于您在示例中捕获了异常(而不是再次抛出),因此外部代码假定一切正常,因此您应该返回一些有用的东西。
If you need to catch the exception there and do somthing that's all fine, but if it's still an error case you should also throw it, or a different exception, perhaps with the one you just caught as InnerException.
如果您需要在那里捕获异常并执行某些操作,那一切都很好,但是如果它仍然是一个错误情况,您也应该抛出它,或者另一个异常,也许是您刚刚作为 InnerException 捕获的异常。
回答by zaczap
i'd assume you can still set the message, then return null or whatever the c# equivalent is
我假设您仍然可以设置消息,然后返回 null 或任何等效的 c#
public DataTable ReturnSomething(){
try {
//logic here
return ds.Tables[0];
} catch (Exception e) {
ErrorString=e.Message;
return null;
}
}
回答by Canavar
How about this :
这个怎么样 :
public DataTable ReturnSomething(out string errorString)
{
errorString = string.Empty;
DataTable dt = new DataTable();
try
{
//logic here
dt = ds.Tables[0];
}
catch (Exception e)
{
errorString = e.Message;
}
return dt;
}
回答by kemiller2002
If you are going to head the "don't throw an exception route" (which I am not necessarily reccomending), you could follow the TryParse approach MS uses.
如果您打算采用“不要抛出异常路由”(我不一定推荐),则可以遵循 MS 使用的 TryParse 方法。
Something like:
就像是:
private string FillDataTable(out DataTable results)
{
try
{
results = new DataTable(); //something like this;
return String.Empty;
}
catch (Exception ex)
{
results = null;
return ex.Message;
}
}
}
回答by Chris Ammerman
The ErrorString variable looks suspiciously like an error code variable. Recommended practice is to use exceptions to pass error information directly, where necessary, rather than storing things off into error codes.
ErrorString 变量看起来很像错误代码变量。推荐的做法是在必要时使用异常直接传递错误信息,而不是将内容存储到错误代码中。
You are effectively doing the same thing with your ErrorString as you would be if you just let the exception be caught by the caller: removing the responsibility of responding to an error from the method itself. This is a good goal to have. But the use of an error string doesn't gain you anything over the use of an exception. In fact, you lose information this way. There are any number of types of errors that could occur, and many have special exceptions associated with them, with their own special properties to hold contextual info about the failure. By just storing off the message in a String, you're losing this information.
您对 ErrorString 进行了有效的处理,就像您只是让调用者捕获异常一样:从方法本身中移除响应错误的责任。这是一个很好的目标。但是使用错误字符串不会比使用异常获得任何好处。事实上,你会以这种方式丢失信息。可能会发生多种类型的错误,并且许多错误都有与之关联的特殊异常,它们具有自己的特殊属性来保存有关失败的上下文信息。仅将消息存储在字符串中,就会丢失这些信息。
So unless your goal is specifically to hide the type of error that is occurring from the caller, you can only gain by letting the exception through.
因此,除非您的目标是专门隐藏调用者发生的错误类型,否则您只能通过让异常通过来获得收益。
Another thing to consider is whether this is truly an error scenario. If it is, it's very unlikely that your calling method is going to care at all what the return value is. In which case, you have nothing to worry about by just letting the exception go and not returning anything. If it's NOT really an error scenario, and the caller is just going to continue on and do something else, well, that's for the caller to decide, right? There's still not much benefit to obtain by returning an error string and a dummy DataTable or a null, over throwing the exception with all its contextual failure info.
另一件需要考虑的事情是这是否真的是一个错误场景。如果是,则您的调用方法不太可能关心返回值是什么。在这种情况下,您无需担心,只需让异常消失而不返回任何内容即可。如果这不是一个真正的错误场景,而调用者只是继续做其他事情,那么,这由调用者决定,对吗?通过返回错误字符串和虚拟数据表或空值,与抛出异常及其所有上下文失败信息相比,仍然没有太多好处。