2012-03-22 3 views
17

예외를 throw하려는 중입니다 (try catch 블록을 사용하지 않고) 예외가 발생하면 바로 프로그램이 완료됩니다. 예외를 던진 다음 프로그램을 계속 실행하는 방법이 있습니까? 나는 다른 클래스에서 정의한 InvalidEmployeeTypeException을 던집니다. 그러나이 예외가 발생하면 프로그램을 계속 진행하고 싶습니다.자바에서 예외가 throw 된 후 계속 실행

private void getData() throws InvalidEmployeeTypeException{ 

    System.out.println("Enter filename: "); 
    Scanner prompt = new Scanner(System.in); 

    inp = prompt.nextLine(); 

    File inFile = new File(inp); 
    try { 
     input = new Scanner(inFile); 
    } catch (FileNotFoundException ex) { 
     ex.printStackTrace(); 
     System.exit(1); 
    } 

    String type, name; 
    int year, salary, hours; 
    double wage; 
    Employee e = null; 


    while(input.hasNext()) { 
     try{ 
     type = input.next(); 
     name = input.next(); 
     year = input.nextInt(); 

     if (type.equalsIgnoreCase("manager") || type.equalsIgnoreCase("staff")) { 
      salary = input.nextInt(); 
      if (type.equalsIgnoreCase("manager")) { 
       e = new Manager(name, year, salary); 
      } 
      else { 
       e = new Staff(name, year, salary); 
      } 
     } 
     else if (type.equalsIgnoreCase("fulltime") || type.equalsIgnoreCase("parttime")) { 
      hours = input.nextInt(); 
      wage = input.nextDouble(); 
      if (type.equalsIgnoreCase("fulltime")) { 
       e = new FullTime(name, year, hours, wage); 
      } 
      else { 
       e = new PartTime(name, year, hours, wage); 
      } 
     } 
     else { 


      throw new InvalidEmployeeTypeException(); 
      input.nextLine(); 

      continue; 

     } 
     } catch(InputMismatchException ex) 
      { 
      System.out.println("** Error: Invalid input **"); 

      input.nextLine(); 

      continue; 

      } 
      //catch(InvalidEmployeeTypeException ex) 
      //{ 

      //} 
     employees.add(e); 
    } 


} 

답변

4

을이 시도 :

try 
{ 
    throw new InvalidEmployeeTypeException(); 
    input.nextLine(); 
} 
catch(InvalidEmployeeTypeException ex) 
{ 
     //do error handling 
} 

continue; 
+25

이것이 예외 사용 방법의 좋은 예라고 생각하지 않습니까? – manub

+1

이것은 완벽하게 작동했습니다. 나는 오류 처리를 처리하고 실행을 계속할 수 있었다. –

+0

왜이 코드가 정중하게 표현 된 오프닝 코멘트에서 '좋은 예가 아닌가'를 평가하는 데 시간이 걸렸다. 'input.nextLine();'은 절대로 실행되지 않습니다. – Reg

30

예외를 throw하면 메서드 실행이 중지되고 예외가 호출자 메서드에 throw됩니다. throw은 항상 현재 메소드의 실행 흐름을 중단합니다. try/catch 블록은 예외를 throw 할 수있는 메서드를 호출 할 때 작성할 수있는 것이지만 예외를 throw하는 것은 비정상적인 조건으로 인해 메서드 실행이 종료되었음을 의미하며 예외는 호출자 메서드에 해당 조건을 알립니다.

예외에 대한이 튜토리얼을 찾아 작동 방식 - http://docs.oracle.com/javase/tutorial/essential/exceptions/

4

당신은 당신이 오류가 발생 할 방법이 있지만 몇 가지 정리를하고 싶은 경우 메서드를 미리 try 블록 안에 예외를 throw하는 코드를 넣은 다음 catch 블록에 정리를 넣은 다음 오류를 throw 할 수 있습니다.

try { 

    //Dangerous code: could throw an error 

} catch (Exception e) { 

    //Cleanup: make sure that this methods variables and such are in the desired state 

    throw e; 
} 

이 방법은 try/catch 블록은 실제로 오류를 처리하지 않고, 당신에게 방법을 종료하고 여전히 오류가 호출자에게 전달되는 것을 보장하기 전에 물건을 할 수있는 시간을 제공합니다.

예를 들어, 변수가 메소드에서 변경된 경우 해당 변수가 오류의 원인이 될 수 있습니다. 변수를 되 돌리는 것이 바람직 할 수 있습니다.

관련 문제