Java supports checked exceptions (in addition to unchecked exceptions). C# only supports unchecked exceptions. Checked exceptions force the programmer to either declare the exception thrown in a method, or to catch the thrown exception using a try-catch clause.
Checked exceptions can be helpful for good programming practice, ensuring that all errors are dealt with. However Anders Hejlsberg, chief C# language architect, and others argue that they were to some extent an experiment in Java and that they haven't been shown to be worthwhile except in small example programs.[9][10]
One criticism is that checked exceptions encourage programmers to use an empty catch block (catch (Exception e) {}), which silently eats exceptions, rather than letting the exceptions propagate to a higher-level exception-handling routine. Another criticism of checked exceptions is that a new implementation of a method may cause unanticipated checked exceptions to be thrown, which is a contract-breaking change. This can happen in methods implementing an interface that only declares limited exceptions, or when the underlying implementation of a method changes. To allow for such unanticipated exceptions to be thrown, some programmers simply declare the method can throw any type of exception ("throws Exception"), which defeats the purpose of checked exceptions. In some cases however, exception chaining can be applied instead; re-throwing the exception in a wrapper exception. For example, if an object is changed to access a database instead of a file, an SQLException could be caught and re-thrown as an IOException, since the caller may not need to know the inner workings of the object.
There are also differences between the two languages in treating the try-finally statement. The finally is always executed, even if thetry block contains control-passing statements like throw or return. In Java, this may result in unexpected behavior if the try block is left by a return statement with some value, and then the finally block that is executed afterwards is also left by a return statement with a different value. C# resolves this problem by prohibiting any control-passing statements like return or break in the finally block.
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 using statement as a syntactic shorthand for this common scenario, in which the Dispose() method of the object of the using is always called.

0 Comments:
Post a Comment