2012-03-22 75 views
17

我试图抛出一个异常(不使用try catch块),并且我的程序在异常抛出后立即完成。有没有办法在抛出异常之后继续执行我的程序?我抛出了我在另一个类中定义的InvalidEmployeeTypeException,但是我希望程序在抛出后继续执行。在java抛出异常后继续执行

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 2012-03-22 17:17:42

+1

这工作完美。我能够处理错误处理并继续执行 – 2012-03-22 17:37:31

+0

我花了一段时间才明白,为什么这段代码在有礼貌地开头的评论中“不是一个好例子”。 'input.nextLine();'从不执行。 – Reg 2017-12-08 13:05:18

30

如果抛出异常,则方法执行将停止,异常将引发到调用方法。 throw总是中断当前方法的执行流程。一个try/catch块是您在调用可能抛出异常的方法时可以编写的内容,但抛出异常仅表示由于异常情况而终止了方法执行,并且异常通知调用方方法。

查找本教程的异常以及它们如何工作 - http://docs.oracle.com/javase/tutorial/essential/exceptions/

4

如果你有,你想抛出一个错误的方法,但你想要做一些清理工作在你的方法,你可以把代码放在try块中,然后把清理放到catch块中,然后抛出错误。

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块是不实际处理错误,但它让你有时间做的东西的方法终止,仍然保证了误差上给调用者才能通过。

这样做的一个例子是如果变量在方法中发生变化,那么该变量就是错误的原因。可能需要恢复变量。