Comparison of C Sharp and Java: Difference between revisions

Content deleted Content added
Finally Blocks and Uncaught Exceptions: There's no need to say that there's no difference, but there is a distinct difference in treatment of "finally"
Line 277:
A common reason for using try-finally blocks is to guard resource managing code, so that precious resources are guaranteed to be released in the finally block. C# features the <code>using</code> statement as a syntactic shorthand for this common scenario, in which the <code>Dispose()</code> method of the object of the <code>using</code> is always called.
 
==== Finally Blocks and Uncaught Exceptions ====
 
Java allows flow of control to leave the <code>finally</code> block of a <code>try</code> statement, regardless of the way it was entered. This can cause another control flow statement (such as <code>return</code>) to be terminated mid-execution. For example:
Both C# and Java handle execution of finally blocks exactly the same when dealing with an uncaught exception.
 
<ref>try
<source lang="java">
{
int foo() {
Console.Out.WriteLine("In Try");
try {
throw new Exception();
return }0;
} finally {
finally
return {1;
}
Console.Out.WriteLine("In Finally");
}
}</ref>
</source>
 
In the above code, the <code>return</code> statement within <code>try</code> block causes control to leave it, and therefore <code>finally</code> block is executed before the actual return happens. However, <code>finally</code> block itself performs a return as well; thus, the original return that caused it to be entered is not actually executed, and the above method returns 1 rather than 0.
 
In C#, no statements which allow control flow to prematurely leave the <code>finally</code> block are allowed, except for <code>throw</code>. In particular, <code>return</code> is not allowed at all, <code>goto</code> is not allowed if the target label is outside the <code>finally</code> block, and <code>continue</code> and <code>break</code> are not allowed if the nearest enclosing loop is outside the <code>finally</code> block.
 
=== Lower level code ===