Checked vs unchecked exceptions
jag via Digitalmars-d
digitalmars-d at puremagic.com
Tue Jun 27 11:14:47 PDT 2017
As Tobias mentioned, there are safety implications to "auto"
behavior. In the example below I am using C# and its "var"
feature:
class A {
public static Employee getFoo() {
return getPoorPerformingEmployee();
}
}
This is your code, in which you are calling A which was written
by someone else:
class B {
var foo = A.getFoo();
foo.fire();
}
Now another programmer changes class A as follows:
class A {
public static Missile getFoo() {
return new Missile();
}
}
Guess what happens now? You intended to fire an employee, but
instead you have fired a missile. The compiler did not catch this
grave mistake because you did not clearly state your intent. Your
class B compiles fine because both Employee and Missile have a
method named fire(). You could have expressed your intent more
clearly like this:
class B {
Employee foo = A.getFoo();
foo.fire();
}
Now the compiler is able to catch your mistake. This is the
reason your code becomes safer when you express your intent
clearly. You should have the option to state your intent clearly
by listing the exceptions that can be thrown by a method.
In dynamic languages like Python there is less ability to state
intent clearly. As a result in such languages fewer bugs can be
caught at compile time. More bugs show up at run time. This may
be acceptable if the program is intended for internal use in a
company, because when the program crashes they can call you to
come and fix it because you are in the next office. But when
reliability is important then the more opportunity there is to
express intent and have the compiler verify your code against
your intent, the better.
More information about the Digitalmars-d
mailing list