try-catch-finally
结构
try {
// code can throw exceptions
} catch (Exception ex) {
// exception hanlder
} finally {
// this block is always executed
}
The interesting point is that, code in the finally block always gets executed regardless of what happens in the try block. That means whether the exceptions throw or not, the Java Virtual Machine always execute code in the finally block. Hence the finally is preferred to clean up resources such as closing files, network connections, database connections and so on.
Let’s see an example program that proves the characteristic of the finally block:
public static void main(String[] args) {
try {
String firstAge = args[0];
System.out.println("First Argument:" + firstAge);
} catch (IndexOutOfBoundsException e) {
System.out.println("There is no argument");
} finally {
System.out.println("Finally gets executed");
}
}
To understand clearly about the benefit of using finally block, consider the following program that writes some text to a file:
public static void main(String[] args) {
FileWriter writer = null;
try {
writer = new FileWriter("name.txt");
writer.write("Hello "); //1
String name = args[0]; //2
writer.write(name); //3
writer.close(); //4
} catch (IOException e) {
e.printStackTrace();
}
}
Look, the line 4 will not be executed in case the line 2 causes an exception (IndexOutOfBoundsException if no argument is passed). If that happens, the try-catch block exits but the file remains opened as line 4 could not be reached.
-
不管发不发生异常都需要执行的动作应该写到finally中
-
The finally block can be used with the try block only (the catch block is missing)
-
只有在try块或catch块中出现对System.exit()的调用时,finally块才不会执行