What is the purpose of “finally” in try/catch/fina

2019-02-03 04:59发布

The syntax will change from language to language, but this is a general question.

What is the difference between this....

try
{
     Console.WriteLine("Executing the try statement.");
     throw new NullReferenceException();
}
catch (NullReferenceException e)
{
     Console.WriteLine("{0} Caught exception #1.", e);
}       
finally
{
     Console.WriteLine("Executing finally block.");
}

and this....

try
{
    Console.WriteLine("Executing the try statement.");
    throw new NullReferenceException();
}
catch (NullReferenceException e)
{
    Console.WriteLine("{0} Caught exception #1.", e);
}        
Console.WriteLine("Executing finally block.");

I keep seeing it being used, so I assume there's a good reason to use finally, but I can't figure out how it's any different from just putting code after the statement since it will still run.

Is there ever a scenario where finally doesn't run?

10条回答
甜甜的少女心
2楼-- · 2019-02-03 05:06

finally runs for both try and catch. It ensures that it will run, but it is not 100% guaranteed it will [some errors stop execution of code]

查看更多
叛逆
3楼-- · 2019-02-03 05:10

finally always always runs. finally is like the catcher that never misses anything. In the example you mentioned, yes finally doesnt add any value. But finally is usually used to dispose/ release resources.

查看更多
4楼-- · 2019-02-03 05:11

try block needs at least one catch or a finally.after executing all catch blocks the finally block will be executed.You can add any logic you need there which should be done ultimately.

查看更多
The star\"
5楼-- · 2019-02-03 05:15

Its a good practice to use finally to handle program crashes. finally will always run .If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.

查看更多
闹够了就滚
6楼-- · 2019-02-03 05:17

In your example, it doesn't make a whole lot of difference.

Picture this, though:

    try
    {
        Console.WriteLine("Executing the try statement.");
        throw new NullReferenceException();
    }
    catch (SomeOtherException e)
    {
        Console.WriteLine("{0} Caught exception #1.", e);
    }       
    finally
    {
        Console.WriteLine("Executing finally block.");
    }

    Console.WriteLine("Executing stuff after try/catch/finally.");

In this case, the catch won't catch the error, so anything after the whole try/catch/finally will never be reached. However, the finally block will still run.

查看更多
爷、活的狠高调
7楼-- · 2019-02-03 05:23

Finally should be used to everything that needs to be done in order to keep a system consistent. This usually means release resources

Finally is always executed, no matter what exception was thrown. It should be used to release resources, in the following cases:

  • Finalize a connection
  • Close a file handler
  • Free memory
  • Close a database connection

Let me give a complete example. Imagine that that you are sending messages through the network. In pseudo-code:

// With finally                  |  //Without finally
try{                             |  try{  
  send_message()                 |    send_message() 
} catch(NetworkError){           |  } catch(NetworkError){ 
  deal_with_exception()          |    deal_with_exception()
} finally {                      |  }
  finalizes_connection()         |  finalizes_connection() 
}                                |

The only difference of both codes is when what is hold in the try block raises an exception that is not NetworkError, for example, MethodNotFound. In the first case, the method finalizes_connection() will be called, and in the second one, it will not.

A connection is naturally done through more than one program. So what happens in the case of a MethodNotFound exception to the other program? In the first case, your program will finish the connection and the other program and it will be happy. In the second case, the other program can be waiting for your response forever. What if the other program can only receive one connection per time? You just bugged the other program as well.

This would also apply for a file, for example, that you opened and other programs wouldn't be able to open for reading (in Windows). And for memory, it is never released and now you have a memory leak.

查看更多
登录 后发表回答