我试图抛出一个异常(不使用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);
}
}
你不觉得这不是一个如何使用异常的好例子吗? – manub 2012-03-22 17:17:42
这工作完美。我能够处理错误处理并继续执行 – 2012-03-22 17:37:31
我花了一段时间才明白,为什么这段代码在有礼貌地开头的评论中“不是一个好例子”。 'input.nextLine();'从不执行。 – Reg 2017-12-08 13:05:18