2014-06-24 2 views
1

질문 :둘 다 수행하는 방법 : outer 메서드에서 예외를 처리하고 inner 메서드의 결과를 반환 하시겠습니까?Java : 예외를 처리하고 내부 메서드에서 결과를 반환하십시오.

제가 가지고 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; 
     } 
    } 
} 

결과 :

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

문제점 : I 느슨한 결과리스트. 나는 예외를 처리하고 outer 메서드에서 [1, 2, 3]리스트를 반환하기를 원한다.

+3

는'Result' 객체 모자는'list'와'exception'을 가지고 만들기를. 그걸 돌려 보내라. –

+0

'outer '메소드의'새로운 HelloWorld(). parseWrapper()'와'parse()'는 모두 구문 오류입니다. 'outer'와'inner'는 원래'parseWrapper'와'parse'라고 가정해야합니까? –

+0

BTW, 'finally'블록에서 돌아 오는 것은 일반적으로 나쁜 것으로 간주됩니다. http://stackoverflow.com/questions/48088/returning-from-a-finally-block-in-java –

답변

6

아니요 - 내부 메서드는 대신 예외를 throw하므로 아무 것도 반환하지 않습니다. 외부 메서드는 단순히 결과가 작동하지 않습니다.

메서드가 예외를 throw하는 경우 일반적으로 메서드의 작업 중 이 없음이 유용 할 것으로 예상됩니다.

당신은 가능한 멀리로 목록을 채우는하려는 경우로 대신하는 방법 목록 을 전달할 수 : 다음

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

를로 전화 :

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

그것은 거의 없다 솔직히 말해서, 좋은 경험이 있다면, 대부분의 예외는 실제로 처리되고 재개 될 수 없습니다. "정리해야 할 것을 해결하고, 작업 단위를 취소"하는 경우가 더 많습니다. 그건 물론 보편적으로 사실이 아니지만, 부분적으로 결과로 얻으려고하는 것은 거의 유용하지 않습니다.

1

당신은 클래스 수준에서 목록 instanciation을 가져올 수 :

public class HelloWorld { 
    private List<Integer> list = new LinkedList<>(); 

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

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

그냥 여러 조심 클래스의 동일한 인스턴스에 액세스, 각 호출에서 같은 목록 인스턴스 덤비는 될 것이다.

하지만 여전히 나는 거기에 예외를 던지는 대신 단지 일부 목록을 반환하는 진짜 이유 궁금 해요 :

if (i % 4 == 0) return list; 
관련 문제