달력

06

« 2018/06 »

  •  
  •  
  •  
  •  
  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
2009.09.17 16:45

Finally clause 삽질예방/Java2009.09.17 16:45


even if another exception is thrown in catch block, finally block is executed before 2nd exception is caught.

Therefore, "every" time control enters try block, finally block is reserved to be run (after finishing try{} and when finished catching. if it is not caught there, then finally block is executed and then jump)

here is a good example.

static void f(int k, int[] A, String S) {
int j = 1 / k;
int len = A.length + 1;
char c;

try {
c = S.charAt(0);
if (k == 10) j = A[3];
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("array error");
throw new InternalError();
} catch (ArithmeticException ex) {
System.out.println("arithmetic error");
} catch (NullPointerException ex) {
System.out.println("null ptr");
} finally {
System.out.println("in finally clause");
}
System.out.println("after try block");
}

Part A: Assume that variable X is an array of int that has been initialized to be of length 3. For each of the following calls to method f, say what (if anything) is printed by f and what, if any, uncaught exceptions are thrown by f.

  1. f(0, X, "hi")
  2. f(10, X, "")
  3. f(10, X, "bye")
  4. f(10, X, null)

The answer is following.


Posted by Kwang-sung Jun