views:

31

answers:

1

I am using Gson to parse Json. What I don't understand what the return type will be if you don't catch the Runtime Exception. I was expecting it to be null, but it is not null when evaluating with a simple if statement.

My code looks something like this:

public X x(final String jsonString) {
   return gson.fromJson(jsonString, X.class);
}

then from another function I call the function:

public void y() {
  final X x = x();
  if (x == null) {
    System.out.println("x == null");
  }
}

I was expecting x to be null, but it isn't because the print statement is not called? What is the value of x? I have solved my problem by using a catch block in the x() function and returning null from inside the catch block. But I am just wondering what the value of function x() is(if any?)? Hopefully I make any sense at all.

+3  A: 

If x() is throwing an exception, the x variable remains uninitialized, since the control flow was interrupted. Without a try/catch, the exception keeps going up the stack and x is never usable. With a try/catch, x is only valid within the block, so if an exception happens it won't be usable.

If you try to do something like:

X x;
try {
    x = x();
} catch(RuntimeException e) {}
if (x == null) {
    ...

you'll get the error "variable x might not have been initialized", since control flow can bypass the assignment

Michael Mrozek