Jan 2021
Takashi Idobe
The method signature here is lying: We’re saying we have a static function that always returns an Integer.
But it can throw an exception too.
What about this?
So it can be null too:
class Main {
public static void main(String args[]) {
div(null, null);
}
public static Integer div(Integer a, Integer b) {
if (a == null || b == null) {
throw new IllegalArgumentException("Divide by Null");
}
try {
return a / b;
} catch (Exception e) {
throw new IllegalArgumentException("Divide by Zero Error");
}
}
}I just wanted to divide two numbers:
The method writer always needs to be cautious of
Reference types (which can be null), and throwing
exceptions:
There’s no way to label functions that can throw Exceptions. The
compiler can help with checked exceptions, but the function
lacks that information in its type signature.
Exceptions are quite unwieldly.
In C++ it’s a little better:
Swift uses Optional<T>s
Swift also allows for exceptions:
It also inverts the C++ standard, which labels that functions cannot throw: All throwable functions can be labeled: