티스토리 뷰

Dev Story/Java

try-catch-finally 순서

Dynatic 2015. 10. 24. 04:19

try - catch - finally

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
public class TryCatchFinal {
    public static void main(String[] args) {
        try{
            System.out.println("before drive");
            drive();
            System.out.println("after drive");
        }
        catch(CustomException e){
            System.out.println("catch");
        }
        finally {
            System.out.println("final");
        }
    }
    public static void drive() throws CustomException {
        System.out.println("before throw in drive");
        if(Math.random() > 0) {
            throw new CustomException();
        }
        System.out.println("after throw in drive");
    }
}
 
class CustomException extends Exception{
 
}
cs


1. try 문에서 에러가 나올 때 까지 라인 단위 코드 실행

2. 에러가 발생하면 그 시점 이후로 catch 문 진입

3. try 가 끝나거나 catch가 끝난 시점에서 finally 진입


실행 결과

before drive

before throw in drive

catch

final


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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 31
글 보관함