How to work with finally?
Finally block guarantees to execute in each and every condition whether it is successful completion of a function or any error has been occurred not matter finally block would execute definitely.But control should come in try block if it did not come in try block and return before try block than finally will not execute.
Example 1
private void Show()
{
try
{
Console.Writeline("In try");
return;
}
catch(Exception ex)
{
throw ex;
}
finally
{
Console.Writeline("Finally");
}
}
Output :- In try Finally
Example 2
private void Show()
{
Console.Writeline("In Function");
try
{
Console.Writeline("In try");
return;
}
catch(Exception ex)
{
throw ex;
}
finally
{
Console.Writeline("Finally");
}
}
Output :- In Function In try Finally
Finally block used for to close any open file or connection or to null the reference type variables or for all type of work that you want to do in each and every condition.
There is some limitation of finally block you can not write return statement there since there is a chance that it may override the actual return statement.
If you write return statement there it will throw a compile time error.
"Control cannot leave the body of a finally clause."
Even you can not modify the return value inside finally block. Though it will not give any error but will not affect output.Since return value already decided before it goes to finally block,
public class ReturnExample
{
private String normalExecution()
{
String result = "";
try
{
result = "Entered try block.";
return result;
}
catch(Exception e)
{
result = result + "Entered Catch block.";
return result;
}
finally
{
result = result + "Entered finally block.";
}
}
public static void main(String[] args)
{
ReturnExample example = new ReturnExample();
String result = example.normalExecution();
Console.Writeline(result);
}
Output :- Entered Try block.
Finally block is not like if or for means in case of if or for there is no need of braces if we have only one line but same is not true for finally. Braces are compulsory for finally.Although you can write only try and catch or try and finally.
These are all correct
try
{
}
catch
{
}
or
try
{
}
finally
{
}
Wednesday, December 1, 2010
Subscribe to:
Post Comments (Atom)
Followers
Link
Labels
Agille
(3)
Angular 2
(96)
Architecture
(7)
ASP .Net
(30)
C#/VB .Net
(161)
Entityframework
(11)
General
(33)
Git
(2)
Hosting
(2)
HTML
(4)
Interview
(12)
Interview-Agile
(1)
Interview-Angular
(25)
Interview-ASP .Net
(3)
Interview-C#
(16)
Interview-JavaScript
(1)
Interview-MVC
(30)
Interview-SQL Server
(4)
Interview-WCF
(2)
Islam
(6)
Java Script
(37)
JQuery
(1)
MVC
(53)
NodeJS
(1)
Puzzles
(1)
React-Native
(3)
Security
(1)
Shayri
(10)
SQL Server
(41)
VC++
(5)
WCF
(21)
Web API
(27)
WPF
(21)
No comments:
Post a Comment