C #: why bother with a “final” sentence?

Possible duplicate:
Why use finally C #?

In C #, what is the point of having a sentence finally?

eg.

try {
        // do something
    }
catch (Exception exc)
    {
        // do something
    }
// do something

Will the code work at the end? What is the block point finally?

+3
source share
7 answers

Finally, for the case when even catch throws an exception, plus it allows you to fix the code of success and failure, finally ALWAYS be executed. IS ALWAYS.

Good, except when the application is killed at the system level or the computer explodes.

+7
source

, , - , , .

.

Try-Catch-finally

:

try
{
   //Open a database connection
}
catch
{
   //Catch exception, database connection failed
}
finally
{
   //Release the opened database connection resources
}
+1

, . Try/Catch/, .

0

, , .

SqlConnection:

SqlConnection conn = new SqlConnection(connString);

try
{        
    conn.Open();

    throw new ArgumentException();
}
catch(SqlException ex)
{
}

SqlConnection , SqlException, ArgumentException . finally, , finally :

try
{        
    conn.Open();

    throw new ArgumentException();
}
catch(SqlException ex)
{
}
finally
{
    conn.Dispose();
}
0

, , , , , . , , , //do something .

0

The code in the finally block is always executed regardless of whether an exception is thrown or not. Code following the exception block may or may not be executed if the path is returned in catch.

0
source

Source: https://habr.com/ru/post/1758441/


All Articles