Java: handle exception and return result from inner method

Question: How to do both: handle exception in outer method and return result of inner method?

I have: two methods which return List:

import java.util.List;
import java.util.LinkedList;

public class HelloWorld {

     public static void main(String[] args){
        System.out.println("Result = " + new HelloWorld().parseWrapper()); 
     }

     public List<Integer> inner() {
         List<Integer> list = new LinkedList<Integer>();
         for (int i = 0; i < 5; i++) {
             if (i % 4 == 0) throw new RuntimeException();
             list.add(i);
         }
         return list;
     }

     public List<Integer> outer() {
         List<Integer> list = null;
         try {
             list = parse();
         } catch (Exception e) {
             System.out.println("Handle exception!");
         } finally {
             return list;
         }
     }
}

Result:

Handle exception!
Result = null // PROBLEM: I DON'T WANT TO LOOSE IT

Problem: I loose result list. I want both: to handle exception and to return [1, 2, 3] list from outer method.

Jon Skeet
people
quotationmark

No - the inner method doesn't return anything, because it throws an exception instead. The outer method simply doesn't have a result to work with.

If a method throws an exception, it's generally expected that none of the work in the method is useful.

If you want to populate a list as far as you can, you could pass the list into the method instead:

public void inner(List<Integer> list) {
    for (int i = 0; i < 5; i++) {
        if (i % 4 == 0) throw new RuntimeException();
        list.add(i);
    }
}

Then call it as:

public List<Integer> outer() {
    List<Integer> list = new LinkedList<>;
    try {
        parse(list);
    } catch (Exception e) {
        System.out.println("Handle exception!");
    } finally {
        return list;
    }
}

It's rarely a good idea, to be honest - in my experience, most exceptions can't really be handled and resumed; it's more a case of "work out what needs to be cleaned up, and the unit of work to abort". That's not universally true of course, but what you're trying to achieve in terms of partial results from a method is pretty rarely useful.

people

See more on this question at Stackoverflow