在java中引发异常后继续执行
我试图抛出一个异常(不使用try-catch块),我的程序在抛出异常后立即完成。有没有一种方法可以在抛出异常后继续执行我的程序?我抛出InvalidEmployeeTypeException,这是我在另一个类中定义的,但我希望程序在抛出后继续在java中引发异常后继续执行,java,exception-handling,throw,Java,Exception Handling,Throw,我试图抛出一个异常(不使用try-catch块),我的程序在抛出异常后立即完成。有没有一种方法可以在抛出异常后继续执行我的程序?我抛出InvalidEmployeeTypeException,这是我在另一个类中定义的,但我希望程序在抛出后继续 private void getData() throws InvalidEmployeeTypeException{ System.out.println("Enter filename: "); Scanner prompt
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
/catch
块,但引发异常只意味着由于异常情况而终止方法执行,异常会将该情况通知调用方方法
查找有关异常及其工作原理的本教程-尝试以下方法:
try
{
throw new InvalidEmployeeTypeException();
input.nextLine();
}
catch(InvalidEmployeeTypeException ex)
{
//do error handling
}
continue;
如果您有一个方法想要抛出错误,但您想事先在方法中进行一些清理,那么可以将引发异常的代码放在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块实际上并没有处理错误,但它在方法终止之前为您提供了执行操作的时间,并且仍然确保将错误传递给调用方
例如,如果方法中的某个变量发生了更改,那么该变量就是错误的原因。可能需要还原变量。您不认为这不是一个关于如何使用异常的好例子吗?这非常有效。我能够处理错误并继续执行。我花了一段时间才明白为什么这段代码在措辞礼貌的开场白中“不是一个好例子”<代码>输入.nextLine()代码>从不执行。