Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Try-catch-finally==== There are also differences between the two languages in treating the {{code|try-finally}} statement. The {{mono|finally}} block is always executed, even if the {{mono|try}} block contains control-passing statements like {{mono|throw}} or {{mono|return}}. In Java, this may result in unexpected behavior, if the {{mono|try}} block is left by a {{mono|return}} statement with some value, and then the {{mono|finally}} block that is executed afterward is also left by a {{mono|return}} statement with a different value. C# resolves this problem by prohibiting any control-passing statements like {{mono|return}} or {{mono|break}} in the {{mono|finally}} block. A common reason for using {{code|try-finally}} blocks is to guard resource managing code, thus guaranteeing the release of precious resources in the finally block. C# features the {{mono|using}} statement as a syntactic shorthand for this common scenario, in which the {{code|Dispose()}} method of the object of the {{mono|using}} is always called. A rather subtle difference is the moment a [[stack trace]] is created when an exception is being thrown. In Java, the stack trace is created in the moment the exception is created. <syntaxhighlight lang=Java> class Foo { Exception up = new Exception(); int foo() throws Exception { throw up; } } </syntaxhighlight> The exception in the statement above will always contain the constructor's stack-trace β no matter how often foo is called. In C# on the other hand, the stack-trace is created the moment "throw" is executed. <syntaxhighlight lang="csharp"> class Foo { Exception e = new Exception(); int foo() { try { throw e; } catch (Exception e) { throw; } } } </syntaxhighlight> In the code above, the exception will contain the stack-trace of the first throw-line. When catching an exception, there are two options in case the exception should be rethrown: {{mono|throw}} will just rethrow the original exception with the original stack, while {{code|throw e}} would have created a new stack trace.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)