Java 教程《語法說明》General Try block
■ General Try block
try {
/* Statements which may throw an exception */
‥‥
}
catch(ExceptionClass1 exceptionObject1) {
/* Statements to do if an exeption of type Throwable 1 is thrown */
‥‥
}
catch(ExceptionClass2 exceptionObject2){
/* Statements to do if an exeption of type Throwable n is thrown */
‥‥
}
‥‥
finally {
/* Statements to do regardless of whether or not an exception is thrown. */
‥‥
}
[說明]
1. try-catch-finally 敘述可處理例外狀況。
try 區塊內的程式碼若是產生例外狀況,則會將程式執行權交由符合的 catch 區塊作處理。
若沒有任何的exception 發生,則會跳過 catch 區塊。
不論是否發生例外狀況,finally 區塊內的程式碼一定會被執行(除非try區塊內使用 System.exit(...) 跳出程式)。
2. 除基本用法外,可使用巢狀try-catch-finally、多重catch區塊、try-finally 變形敘述
[範例]
try {
System.out.println("What is your name?");
String name=console.readLine( );
System.out.println("Hello, " +name+ "!");
}
catch(IOException e) {
System.out.println(e);
System.exit(1);
}