Program logic bugs vs input/environmental errors (checked exceptions)
Bruno Medeiros via Digitalmars-d
digitalmars-d at puremagic.com
Wed Oct 1 07:24:47 PDT 2014
On 29/09/2014 20:28, Sean Kelly wrote:
> Checked exceptions are good in theory but they failed utterly in
> Java. I'm not interested in seeing them in D.
That is the conventional theory, the established wisdom.
But the more I become experienced with Java, over the years, I've become
convinced otherwise.
What has failed is not the concept of checked exceptions per se, but
mostly, the failure of Java programmers to use checked exceptions
effectively, and properly design their code around this paradigm.
Like Jeremy mentioned, if one puts catch blocks right around the
function that throws an exception, and just swallow/forget it there
without doing anything else, then it's totally the programmers fault for
being lazy.
If one is annoyed that often, adding a throws clause in a function will
require adding the same throws clause function to several other
functions, well, that is editing work you have to accept for the sake of
more correctness. But also one should understand there are ways to
mitigate this editing work:
First point is that in a lot of code, is better to have a function throw
just one generic (but checked) exception, that can wrap any other
specific errors/exceptions. If you are doing an operation that can throw
File-Not-Found, Invalid-Path, No-Permissions, IO-Exception, etc., then
often all of these will be handled in the same user-reporting code, so
they could be wrapped under a single exception that would be used in the
throws clause. And so the whole function call chain doesn't need to be
modified every time a new exception is added or removed.
If you're thinking that means adding a "throws Exception" to such
functions in Java, then no. Because this will catch RuntimeExceptions
too (the unchecked exceptions of Java), and these you often want to
handle elsewhere than where you handle the checked exceptions. In this
regard, Java does have a design fault, IMO, which is that there is no
common superclass for checked Exceptions. (there is only for unchecked
exceptions)
The second point, is that even adding (or modifying) the throws clause
of function signatures cause be made much easier with an IDE, and in
particular Eclipse JDT helps a lot. If you have an error in the editor
about a checked exception that is not caught or thrown, you can just
press Ctrl-1 to automatically add either a throws clause, or a
surrounding try-catch block.
--
Bruno Medeiros
https://twitter.com/brunodomedeiros
More information about the Digitalmars-d
mailing list