在java中抛出异常后继续执行

时间:2012-03-22 17:12:39

标签: java exception-handling throw

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

    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);
    }


}

3 个答案:

答案 0 :(得分:32)

如果抛出异常,方法执行将停止,并向调用方法抛出异常。 throw总是中断当前方法的执行流程。当您调用可能引发异常的方法时,您可以编写try / catch块,但抛出异常只是意味着由于异常条件而终止方法执行,并且异常通知该条件的调用方法。

查找有关异常及其工作原理的本教程 - http://docs.oracle.com/javase/tutorial/essential/exceptions/

答案 1 :(得分:5)

试试这个:

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

continue;

答案 2 :(得分: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块实际上并没有处理错误,但是它会让你有时间在方法终止之前做一些事情,并且仍然确保将错误传递给调用者。

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

相关问题