C# try catch 继续执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10820137/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:23:21  来源:igfitidea点击:

C# try catch continue execution

c#try-catch

提问by gardarvalur

I have a question that might seem fairly simple (of course if you know the answer).

我有一个看起来很简单的问题(当然如果你知道答案的话)。

A certain function I have calls another function but I want to continue execution from the caller even though the callee has thrown an exception. Let me give you an example:

我有某个函数调用了另一个函数,但即使被调用者抛出了异常,我也想继续从调用者执行。让我给你举个例子:

something function1()
{
    try
    {
        //some code
        int idNumber = function2();
        //other code that need to execute even if function2 fails
        return something;
    }
    catch(Exception e)
    {//... perhaps something here}
}

EDIT: function1 also has a return statement so nothing can in fact crash on the way

编辑:function1 也有一个 return 语句,所以实际上没有任何东西会在途中崩溃

In function2 I need to do stuff but I only need to log if anything fails, example:

在 function2 中,我需要做一些事情,但我只需要在任何失败时记录,例如:

int function2()
{
    try
    {
        //dostuff
    }
    catch(Exception e)
    {
        //Log stuff to db
    }
}

ok, now my question is, what should I do if I wanted to continue execution in function1 even if function 2 throws an error?

好的,现在我的问题是,如果我想在 function1 中继续执行,即使 function 2 抛出错误,我该怎么办?

Sometimes I mix up if I should do throw; or throw e; or throw nothing at all (leave catch block empty)

有时我会混淆是否应该投掷;或扔e; 或者什么都不扔(将 catch 块留空)

采纳答案by Phillip Schmidt

Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.

将 catch 块留空应该可以解决问题。不过,这几乎总是一个坏主意。一方面,有性能损失,另一方面(这更重要),您总是想知道何时出现错误。

I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expectedfor it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.

我猜想“被调用者”函数失败,在你的情况下,实际上不一定是“错误”,可以这么说。也就是说,它有望为它有时会失败。如果是这种情况,几乎总有一种比使用异常更好的方法来处理它。

There are, if you'll pardon the pun, exceptionsto the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finallyblock and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!

还有,如果你能原谅这个双关语,例外的“规则”,虽然。例如,如果 function2 要调用一个 Web 服务,其结果对于您的页面来说并不是真正必要的,那么这种模式可能没问题。尽管在几乎 100% 的情况下,您至少应该在某处记录它。在这种情况下,我会将它记录在一个finally块中并报告服务是否返回。请记住,像现在对您来说可能没有价值的数据可能会在以后变得有价值!

Last edit (probably):

最后编辑(可能):

In a comment I suggested you put the try/catch insidefunction2. Just thought I would elaborate. Function2 would look like this:

在评论中,我建议您将 try/catch放在function2 中。只是想我会详细说明。Function2 看起来像这样:

public Something? function2()
{
    try
    {
        //all of your function goes here
        return anActualObjectOfTypeSomething;
    }
    catch(Exception ex)
    {
        //logging goes here
        return null;
    }
}

That way, since you use a nullable return type, returning null doesn't hurt you.

这样,由于您使用可空返回类型,因此返回 null 不会伤害您。

回答by kemiller2002

just do this

就这样做

    try
    {
        //some code
     try
     {
          int idNumber = function2();

     }
     finally
     {
       do stuff here....
     }
    }
    catch(Exception e)
    {//... perhaps something here}

For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.

对于所有意图和目的,finally 块将始终执行。现在有几个异常不会实际执行:任务终止程序,并且有一个快速失败安全异常会立即终止应用程序。除此之外,函数 2 将抛出异常,finally 块将执行所需的代码,然后在外部 catch 块中捕获异常。

回答by Jay

Or you can encapsulate the looping logic itself in a try catch e.g.

或者您可以将循环逻辑本身封装在 try catch 中,例如

for(int i = function2(); i < 100 /*where 100 is the end or another function call to get the end*/; i = function2()){

    try{
     //ToDo
    }
    catch { continue; }    

}

Or...

或者...

try{ 
    for(int i = function2(); ; ;) {
        try { i = function2(); return; } 
        finally { /*decide to break or not :P*/continue; } }
} catch { /*failed on first try*/ } finally{ /*afterwardz*/ }

回答by Yannis

Why cant you use the finally block?

为什么不能使用 finally 块?

Like

喜欢

try {

} catch (Exception e) {

  // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

} finally { 

 // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

}

EDIT after question amended:

问题修改后编辑:

You can do:

你可以做:

int? returnFromFunction2 = null;
    try {
        returnFromFunction2 = function2();
        return returnFromFunction2.value;
        } catch (Exception e) {

          // THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK

        } finally { 

        if (returnFromFunction2.HasValue) { // do something with value }

         // THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT

        }

回答by Keiichi

Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

你的意思是你想在 function1 中执行代码而不管 function2 是否抛出异常?你看过finally块吗?http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

回答by Mark Adesina Omoniyi

In your second function remove the e variable in the catch block then add throw.

在您的第二个函数中,删除 catch 块中的 e 变量,然后添加 throw。

This will carry over the generated exception the the final function and output it.

这会将生成的异常结转到最终函数并输出。

Its very common when you dont want your business logic code to throw exception but your UI.

当您不希望您的业务逻辑代码抛出异常但您的 UI 时,这很常见。