Will code in finally run after a redirect?

后端 未结 10 1311
别跟我提以往
别跟我提以往 2021-01-02 11:08

Take for example the following code:

   try
   {
      Response.Redirect(someurl);
    }
    finally
    {
       // Will this code run?
    }
相关标签:
10条回答
  • 2021-01-02 11:48

    Try this:

    try
    {
      Response.Redirect("http://www.google.com");
    }
    finally
    {
       // Will this code run?
      // yes :)
      Response.Redirect("http://stackoverflow.com/questions/3668422/will-code-in-finally-run-after-a-redirect");
    
    }
    
    0 讨论(0)
  • 2021-01-02 11:48

    The general rule is that the code in finally will be applied in all cases (try/catch)

    0 讨论(0)
  • 2021-01-02 11:49

    Yes.

    Try it and see!

    0 讨论(0)
  • 2021-01-02 11:49

    It will run. Response.Redirect actually throws a ThreadAbortException, so that's why code after that will not run (except anything in a finally block of course).

    0 讨论(0)
  • 2021-01-02 11:53

    Why do you not just try it?

    finally always runs, except in these extreme scenarios:

    • Total application crash, or application termination (e.g. FailFast())
    • A limited number of serious exceptions
    • Threads getting terminated (eg. Thread.Abort())
    • Hardware failure (e.g. machine losing power)
    • Infinite loop inside the try-block (which ultimately results in application termination)
    0 讨论(0)
  • 2021-01-02 11:58

    It will indeed. See this MSDN article: Finally always executes

    0 讨论(0)
提交回复
热议问题