| |
| Posted by Steven Schveighoffer in reply to webdev | PermalinkReply |
|
Steven Schveighoffer
Posted in reply to webdev
| On 9/23/20 12:53 PM, webdev wrote:
> Trans some Java code to D, so far has lots of issues, this time I will focus on Exception.
>
> interface Widget {
> string name();
> }
>
> Widget createWidget() {
> return null;
> }
>
> void test() {
> createWidget().name();
> }
>
> The similar code in Java will throw NullPointerException, but in D it
> will throw object.Error, how do I know it was caused by null?
No null pointer exceptions in D (you can get them on Linux, but by enabling a non-portable feature of the runtime).
D relies on segfault to halt your program. In debug mode, on some platforms, it might throw an Error (I think on Windows only).
Null pointer dereferences are considered a programming error and not recoverable. Do not try to catch an Error.
> And is it possible to override callback like onOutOfMemoryError & onRangeError?
I believe if you define these functions extern(C) in your app they will be used.
> In Java you can catch multi exception like
>
> try {
> ...
> } catch (A | B e) {
> ...
> }
>
> can trans to:
> try {
> ...
> } catch (A e) {
> ...
> } catch (B e) {
> ...
> }
>
> or:
> try {
> ...
> } catch (Throwable t) {
> if (t is A | B) {
> ...
> } else {
> throw t;
> }
> }
>
> which one is better, will it has side effect?
1. Don't catch Throwable, as Errors should not be caught. Catch Exception instead
2. Your code should work as expected I think. You can rethrow exceptions.
-Steve
|