Reputation: 273
For example:
FileOutputStream("file")
would compile in Kotlin, but in Java it would give a compiler error. Why?
Upvotes: 5
Views: 5143
Reputation: 3839
Kotlin does away with Java's checked exceptions. Exceptions checked at compile time and declared in method signatures, though familiar to Java developers, are widely considered a failed experiment outside and to some degree inside the Java community.
So Kotlin did away with them, and with some of the boilerplate associated with using resources (like FileOutputStream
) with the .use method shorthand for Java 7's try-with-resources.
Upvotes: 4
Reputation: 1979
It can be difficult to answer without letting some opinions interfere. I will just say that Kotlin is aimed at large software projects and give you what the Kotlin team claims regarding checked exceptions (from https://kotlinlang.org/docs/reference/exceptions.html):
Checked Exceptions
Kotlin does not have checked exceptions. There are many reasons for this, but we will provide a simple example.
The following is an example interface of the JDK implemented by StringBuilder class:
Appendable append(CharSequence csq) throws IOException; What does this signature say? It says that every time I append a string to something (a StringBuilder, some kind of a log, a console, etc.) I have to catch those IOExceptions. Why? Because it might be performing IO (Writer also implements Appendable)… So it results into this kind of code all over the place:
try { log.append(message) } catch (IOException e) { // Must be safe }
And this is no good, see Effective Java, Item 65: Don't ignore exceptions.
Bruce Eckel says in Does Java need Checked Exceptions?:
Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result – decreased productivity and little or no increase in code quality.
Other citations of this sort:
Java's checked exceptions were a mistake (Rod Waldhoff)
The Trouble with Checked Exceptions (Anders Hejlsberg)
Upvotes: 3