当前位置: 首页 > 面试题库 >

在Java中引发异常后继续执行

程皓轩
2023-03-14
问题内容

我正在尝试引发异常(不使用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);
    }


}

问题答案:

试试这个:

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

continue;


 类似资料:
  • 问题内容: 我的示例代码如下: 我的要求是,在捕获到异常之后,我要处理数组的其余元素。我怎样才能做到这一点? 问题答案: 您的代码应如下所示:

  • 问题内容: 一旦在此代码中捕获到异常,该方法就会运行,但是一旦我输入一个数字,程序就会关闭,并显示“生成成功”消息。一旦发生异常,是否有任何方法可以返回while循环? 问题答案: 将 try / catch 放入 while循环中 :

  • EDIT应该返回true或false,但它的抛出错误

  • 问题内容: 我有这段代码。我想回到循环的起点,并再次要求用户输入。但是,它总是循环而不停止请求输入。我的代码有什么问题?谢谢 问题答案: 从http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28int%29: “如果翻译成功,则扫描程序将前进经过匹配的输入。” 啊,但是如果翻译是什么 不是 成功的?在这种

  • 问题内容: 我正在将数据从旧版系统迁移到我们的新应用程序(在Oracle数据库10gR2上运行)。作为迁移的一部分,我正在研究一个脚本,该脚本将数据插入应用程序使用的表中。 导入的数据行数成千上万,并且源数据不是干净的(NOT NULL列中的异常为空,等等)。因此,在通过脚本插入数据时,每当发生此类异常时,脚本就会突然结束,并且整个事务都会回滚。 有没有一种方法可以继续插入行干净的数据?使用或不是

  • 问题内容: 如何使PHP 5.2(以apache mod_php运行)向客户端发送完整的HTTP响应,然后再继续执行操作一分钟? 长话说: 我有一个PHP脚本,该脚本必须执行一些较长的数据库请求并发送电子邮件,这需要45到60秒才能运行。这个脚本由我无法控制的应用程序调用。我需要该应用程序报告从PHP脚本收到的任何错误消息(主要是无效的参数错误)。 该应用程序的超时延迟小于45秒(我不知道确切的值