The execution order of try catch and finally the block

I have a lot of confusion with the order of trying to catch and finally execute the block.

I also want to know when I should use the catch try block and what I should put in the catch try block, I also want to know if some exception comes in the try block, then if the action is executed to execute the try block, and then one is executed by the first catch, or finally (which is always executed), and after performing these two actions, control returns to try to block or leave it forever.

+6
c #
source share
4 answers

If you have ( note: this is not valid C #, see example below):

try { // ... some code: A } catch(...) { // ... exception code: B } finally { // finally code: C } 

Code A will be executed. If all goes well (i.e., no exceptions will be thrown at run time A), it will finally be completed, so the C code will be executed. If an exception is thrown when A is executed, then it goes to B, and then finally to C.

As an example, here is the valid C # code code from http://msdn.microsoft.com/en-us/library/dszsf989.aspx :

 public class EHClass { void ReadFile(int index) { // To run this code, substitute a valid path from your local machine string path = @"c:\users\public\test.txt"; System.IO.StreamReader file = new System.IO.StreamReader(path); char[] buffer = new char[10]; try { file.ReadBlock(buffer, index, buffer.Length); } catch (System.IO.IOException e) { Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message); } finally { if (file != null) { file.Close(); } } // Do something with buffer... } } 

The reason for using try / catch / in the end is to prevent your program from crashing if there is an error in some code (A in the example above). If there is a problem, you can use the catch part to catch the problem and do something useful, for example, tell the user, register an exception in the log file, try again or try something else that, in your opinion, might work instead You tried initially.

finally used to provide some cleanup. For example. You can try to open the file and read it. If the opening succeeds but the reading fails, you will have an open file. In this case, you need to close it, which you would do in the finally block - this block always starts, guaranteeing the closing of the file.

Take a look here for more information:

+6
source share

You should almost never use try / catch.

You should only use catch tags that you can fix, and only when you expect them. Otherwise, let the caller handle the exception - or not.

If used, any catch are executed first - only one of them.

Then finally is executed.


It has been said better in many places, but I will try. The following code:

 try { // Do something here } catch (Exception ex) { MessageBox.Show("Friendly error message"); } 

does not correct the exception. It hides the exception, so the problem will never be fixed. This code has no idea which exception was thrown, because it will catch all of them, and it does nothing to fix the problem - it just tells the user polite fiction.

The fact is that the above code should be replaced with the following:

 // Do something here 

Thus, if the caller of this method knows how to fix certain problems, the caller can fix them. You will not remove this option from the caller.

If the caller does not know how to fix the problem, then the caller should also not catch the exception.


Here is an example (from MSDN) of using exceptions in a reasonable way. This is a modified form of the example in the SmtpFailedRecipientsException Class documentation.

 public static void RetryIfBusy(string server) { MailAddress from = new MailAddress(" ben@contoso.com "); MailAddress to = new MailAddress(" jane@contoso.com "); using ( MailMessage message = new MailMessage(from, to) { Subject = "Using the SmtpClient class.", Body = @"Using this feature, you can send an e-mail message from an application very easily." }) { message.CC.Add(new MailAddress(" Notifications@contoso.com ")); using (SmtpClient client = new SmtpClient(server) {Credentials = CredentialCache.DefaultNetworkCredentials}) { Console.WriteLine("Sending an e-mail message to {0} using the SMTP host {1}.", to.Address, client.Host); try { client.Send(message); } catch (SmtpFailedRecipientsException ex) { foreach (var t in ex.InnerExceptions) { var status = t.StatusCode; if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable) { Console.WriteLine("Delivery failed - retrying in 5 seconds."); System.Threading.Thread.Sleep(5000); // Use better retry logic than this! client.Send(message); } else { Console.WriteLine("Failed to deliver message to {0}", t.FailedRecipient); // Do something better to log the exception } } } catch (SmtpException ex) { // Here, if you know what to do about particular SMTP status codes, // you can look in ex.StatusCode to decide how to handle this exception // Otherwise, in here, you at least know there was an email problem } // Note that no other, less specific exceptions are caught here, since we don't know // what do do about them } } } 

Note that this code uses try / catch to surround a small piece of code. Inside this try / catch block, if a SmtpException or SmtpFailedRecipientsException is thrown, we know what to do with it. If, for example, we were to catch an IOException , we would not know what this means, or what to do about it. Any exception that you do not really know how to fix should not be caught, except, perhaps, to add information to the exception, for registration and retronization.

+4
source share

A try ... catch used to throw exceptions. In the try block, you put code that you expect can throw an exception.

If an exception does not occur, the code in the try block exits as expected. If there is a finally block that will be executed next.

If an exception occurs, execution jumps to the beginning of the first matching catch . Upon completion of this code, the final block is executed (if it exists). Execution does not return to the try block.

+4
source share

Here is an example:

 try { someFunctionThatWorks(); functionThatThrowsAnException(); // As soon as this function throws an exception we are taken to the catch block anotherFunction(); // <-- This line will never get executed } catch(Exception e) { // Here you can handle the exception, if you don't know how to handle it you should not be catching it // After this you will not be taken back to the try block, you will go right to the finally block } finally { // Code here is always executed at the very end, regardless of whether an exception was thrown or not } 
+1
source share

All Articles