try - catch -finally maybe not that simple.
principle:
1) finally block will be operated regardless of return clause. Even it returns in the inner catch block, but outer finally block will still be operated no matter what.
2)
3) return will quite from current position and return control back to the main method.
4) finally block will be operated regardless if there is or not an exception caught.
5) FileNotFoundException is a checked exception.
6) IndexOutOfBoundsException is a un-checked (Runtime) exception, I explicitly catch it here.
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; /** * * @author YNZ */ public class TasteEx { /** * @param args the command line arguments */ public static void main(String[] args) { try { try { FileReader fr = new FileReader(new File("test.txt")); } catch (FileNotFoundException ex) { System.out.println("File not found"); return; } finally { System.out.println("inner final"); } System.out.println("try outer"); int[] ary = new int[2]; ary[0] = 10; ary[5] = 20; } catch (IndexOutOfBoundsException ex) { System.err.println("Index out of bounds"); } finally { System.out.println("outer final"); } System.out.println("next task"); } }
How about moving return also in the finally block?
this gives a compiling error, for //3 cannot be reached.
public static void main(String[] args) { try { try { FileReader fr = new FileReader(new File("test.txt")); } catch (FileNotFoundException ex) { System.out.println("File not found"); return; //1 } finally { System.out.println("inner final"); return; //2 } System.out.println("try outer"); //3 int[] ary = new int[2]; ary[0] = 10; ary[5] = 20; } catch (IndexOutOfBoundsException ex) { System.err.println("Index out of bounds"); } finally { System.out.println("outer final"); } System.out.println("next task"); } }
No comments:
Post a Comment