試試......抓住......最後
try { ... } catch ( ... ) { ... }
控制結構用於處理異常 。
String age_input = "abc";
try {
int age = Integer.parseInt(age_input);
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Sorry, you can't vote yet.");
}
} catch (NumberFormatException ex) {
System.err.println("Invalid input. '" + age_input + "' is not a valid integer.");
}
這將列印:
輸入無效。 ‘abc’不是有效整數。
在 catch
之後可以新增 finally
子句。無論是否丟擲異常,都將始終執行 finally
子句。
try { ... } catch ( ... ) { ... } finally { ... }
String age_input = "abc";
try {
int age = Integer.parseInt(age_input);
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Sorry, you can't vote yet.");
}
} catch (NumberFormatException ex) {
System.err.println("Invalid input. '" + age_input + "' is not a valid integer.");
} finally {
System.out.println("This code will always be run, even if an exception is thrown");
}
這將列印:
輸入無效。 ‘abc’不是有效整數。
即使丟擲異常,也始終會執行此程式碼