Little doubt about try catch block in C sharp

I am using try catch and finally in my project. my doubt is here ... why do we need to use the finally block, in fact, if you do not use the final block, then the codes will be executed after the catch lock. therefore, we can do codes (do resources for free) after catch is blocked. this will be executed even if an exception occurs. So, is there an advantage if we use a finally block ?

+5
source share
7 answers

According to the answer of this previous SO Post:

The code inside the finally block will execute regardless of whether there is an exception. This happens very conveniently when it comes to certain household functions required to always work as closing compounds.

+7
source

I think you are talking about this:

try {
  // do something that might throw exception
}
catch (Exception) {
  // take care of exception
}
finally {
  // what is the point of this?
}

If you handle all possible exceptions in a block catch, the only reason you might need a block finallyis to intercept statements returnfrom the block try.

Thanks to @dthorpe: finally will also intercept the exception / return statement from the block catch.

+1
source

catch .

finally, , . finally, , , , , , .

, . , : ) catch , , , ) catch . , catch, .

catch, , .

+1

finally . GC Dispose , "try"

0

Finally , exception. , Database Connection Dispose Finally.

0

:

String doSomething()
{
  SqlConnection conn;

  try {
    conn = new SqlConnection();

    // SQL stuff

    return result;
  }
  catch(Exception ex) { AddToLog(ex);  }
  finally {
    if (conn != null)
      conn.Dispose();
  }

  return null;
}

, SQL, .

0

, , , catch, , . , - catch, , - .

, //- . catch , , catch ( finally), .

Since there is a possibility that the code in some specific scenarios will not be executed, the final block is your insurance to carry out the critical actions you need. You will need to identify such cases, and there is no such rule that every catch try block must have a final one.

0
source

All Articles