R D*_*abh 22 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);
}
}
Run Code Online (Sandbox Code Playgroud)
man*_*nub 34
如果抛出异常,方法执行将停止,并向调用方法抛出异常.throw
总是中断当前方法的执行流程.当你调用一个可能引发异常的方法时,你可以写一个try
/ catch
block,但抛出异常只是意味着方法执行因异常条件而终止,异常通知调用者方法该条件.
查找有关异常及其工作原理的本教程 - http://docs.oracle.com/javase/tutorial/essential/exceptions/
试试这个:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
94216 次 |
最近记录: |