Finally block C# with Example



Finally block C# with Example

try 
{ 
/* code that could throw an exception */ 
} 
catch (Exception) 
{ 
/* handle the exception */ 
} 
finally 
{ 
/* Code that will be executed, regardless if an exception was thrown / caught or not */ 
} 
The try / catch / finally block can be very handy when reading from files. 
For example: 
FileStream f = null; 
try 
{ 
f = File.OpenRead("file.txt"); 
/* process the file here */ 
 

} 
finally 
{ 
f?.Close(); // f may be null, so use the null conditional operator. 
} 
A try block must be followed by either a catch or a finally block. However, since there is no catch block, the 
execution will cause termination. Before termination, the statements inside the finally block will be executed. 
In the file-reading we could have used a using block as FileStream (what OpenRead returns) implements 
IDisposable. 
Even if there is a return statement in try block, the finally block will usually execute; there are a few cases where 
it will not: 
When a StackOverflow occurs. 
Environment.FailFast 
The application process is killed, usually by an external source. 

0 Comment's

Comment Form

Submit Comment