www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Java to D - exception

reply webdev <fake test.com> writes:
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?

And is it possible to override callback like onOutOfMemoryError & 
onRangeError?

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?
Sep 23 2020
next sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
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
Sep 23 2020
prev sibling parent Dominikus Dittes Scherkl <dominikus scherkl.de> writes:
On Wednesday, 23 September 2020 at 16:53:05 UTC, webdev wrote:
 Trans some Java code to D, so far has lots of issues,
Please, use the learn forum for stuff like this.
Sep 24 2020