c# - order of execution of try catch and finally block -


i having big confusion order of try, catch , block execution.

i want know when should use try catch block , should put in try catch block, want know if exception comes in try block if action taken corresponding try block 1 executed first catch or (which executed), , after execution of these 2 does control return try block or abandon forever.

if have (note: not valid c#, see below valid example):

try {    // ... code: } catch(...) {    // ... exception code: b } {    // code: c } 

code going executed. if goes (i.e. no exceptions thrown while executing), going go finally, code c going executed. if exception thrown while executed, go b , c.

as example, here's valid c# code block http://msdn.microsoft.com/en-us/library/dszsf989.aspx:

public class ehclass {     void readfile(int index)     {         // run code, substitute valid path 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 {0}. message = {1}", path, e.message);         }                 {             if (file != null)             {                 file.close();             }         }         // buffer...     } } 

the reason use try/catch/finally prevent program fail if there error in code (a in above example). if there problem, can use catch part catch problem , useful, such inform user, log exception log file, try again or try different suppose might work instead of tried originally.

finally used ensure cleanup performed. e.g. in might try open file , read it. if opening succeeds, read fails, have open file dangling. in case have closed, in finally block - block gets executed, guaranteeing closing of file.

take here more info:


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -