[英]continuing execution after an exception is thrown in java
我正在嘗試拋出異常(不使用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);
}
}
如果拋出異常,方法執行將停止,並向調用方法拋出異常。 throw
總是中斷當前方法的執行流程。 當你調用可能引發異常的方法時,你可以寫一個try
/ catch
塊,但是拋出異常只意味着方法執行因異常條件而終止,並且異常通知調用者方法該條件。
查找有關異常及其工作原理的本教程 - http://docs.oracle.com/javase/tutorial/essential/exceptions/
試試這個:
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塊實際上並沒有處理錯誤,但是它讓你有時間在方法終止之前做一些事情,並且仍然確保將錯誤傳遞給調用者。
例如,如果變量在方法中發生變化,那么該變量就是導致錯誤的原因。 可能需要恢復變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.