Checked vs unchecked exceptions

jag via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 26 11:31:50 PDT 2017


On Monday, 26 June 2017 at 17:43:08 UTC, Moritz Maxeiner wrote:
>> Here's the point: with checked exceptions good programmers can 
>> write good code.
>
> With checked exceptions any programmer is forced to
> a) annotate every single function with the complete aggregate 
> of the exceptions that may be thrown by itself or the functions 
> it calls
> b) violate checked exceptions and limit its callers by marking 
> itself as throwing a parent exception
>

Here's an example C# pseudocode to illustrate the problem:

Programmer A writes this C# code:

class A {
    public static void startFoo() {
       if (/* Foo is not installed */)
           throw new FooNotInstalled();
       // ...
    }
}

Programmer B calls the above code like this:

class B {
    try {
       A.startFoo();
    }
    catch (FooNotInstalled) {
       // Tell user to purchase Foo
    }
}

Later programmer A updates his code because there are newer 
versions of Foo and he needs the newest version:

class A {
    public static void startFoo() {
       if (/* Foo is not installed */)
           throw new FooNotInstalled();
       if (/* Foo version is too old */)
           throw new FooVersionTooOld();
       // ...
    }
}

Now the code written by Programmer B crashes even though it 
compiles file. That's bad.

Had this been Java, programmer would be would be alerted to the 
fact that he needs to decide what do do if the version of Foo is 
too old. This is good.

So listing exceptions that can be thrown is a good thing because 
it helps you write more reliable code. If you are lazy you can 
always defeat the system by declaring your method as throwing a 
parent (or the root) exception class, in which case it is no 
worse than C#.



More information about the Digitalmars-d mailing list