在java中抛出异常后继续执行 [英] continuing execution after an exception is thrown in java

查看:2482
本文介绍了在java中抛出异常后继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to throw an exception (without using a try catch block) and my program finishes right after the exception is thrown. Is there a way that after I throw the exception, to then continue execution of my program? I throw the InvalidEmployeeTypeException which I've defined in another class but I'd like the program to continue after this is thrown.

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


}


推荐答案

尝试这样:

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

continue;

这篇关于在java中抛出异常后继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆