Why use finally in C#?

2020-01-24 03:22发布

Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?

13条回答
爷、活的狠高调
2楼-- · 2020-01-24 04:11

The finally block is valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

查看更多
太酷不给撩
3楼-- · 2020-01-24 04:12

Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:

try
{
    // Code here that might throw an exception...

    if (arbitraryCondition)
    {
        return true;
    }

    // Code here that might throw an exception...
}
finally
{
    // Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}

This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a using block is often better in this case.

查看更多
迷人小祖宗
4楼-- · 2020-01-24 04:13

i will explain the use of finally with a file reader exception Example

  • with out using finally
try{

  StreamReader strReader = new StreamReader(@"C:\Ariven\Project\Data.txt");
  Console.WriteLine(strReader.ReadeToEnd());
  StreamReader.Close();
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}

in the above example if the file called Data.txt is missing, an exception will be thrown and will be handled but the statement called StreamReader.Close(); will never be executed.
Because of this resources associated with reader was never released.

  • To solve the above issue, we use finally
StreamReader strReader = null;
try{
    strReader = new StreamReader(@"C:\Ariven\Project\Data.txt");
    Console.WriteLine(strReader.ReadeToEnd());
}
catch (Exception ex){
    Console.WriteLine(ex.Message);
}
finally{
    if (strReader != null){
        StreamReader.Close();
    }
}

Happy Coding :)

Note: "@" is used to create a verbatim string, to avoid error of "Unrecognized escape sequence". The @ symbol means to read that string literally, and don't interpret control characters otherwise.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-01-24 04:14

any time you use unmanaged code requests like stream readers, db requests, etc; and you want to catch the exception then use try catch finally and close the stream, data reader, etc. in the finally, if you don't when it errors the connection doesn't get closed, this is really bad with db requests

 SqlConnection myConn = new SqlConnection("Connectionstring");
        try
        {
            myConn.Open();
            //make na DB Request                
        }
        catch (Exception DBException)
        {
            //do somehting with exception
        }
        finally
        {
           myConn.Close();
           myConn.Dispose();
        }

if you don't want to catch the error then use

 using (SqlConnection myConn = new SqlConnection("Connectionstring"))
        {
            myConn.Open();
            //make na DB Request
            myConn.Close();
        }

and the connection object will be disposed of automatically if there is an error, but you don't capture the error

查看更多
在下西门庆
6楼-- · 2020-01-24 04:14

Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.

For example:

try
{
    // exception (or not)
}
finally
{
    // clean up always
}
查看更多
干净又极端
7楼-- · 2020-01-24 04:15

Control Flow of the Finally Block is either after the Try or Catch block.

[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]

with Exception 1 > 2 > 3 > 4 > 5 if 3 has a Return statement 1 > 2 > 3 > 4

without Exception 1 > 2 > 4 > 5 if 2 has a return statement 1 > 2 > 4

查看更多
登录 后发表回答