평범한 개발자 행복한 가족, 패밀리그램

개발/안드로이드

안드로이드 에러 처리 (Java try - catch - finally)

패밀리그램 2016. 12. 1. 22:54

Android Java Error 처리를 위해서는 try - catch와 Log cat을 이용한 

Error 처리를 기본적으로 사용한다.


1
2
3
4
5
6
7
try{
    //Exception
}catch(Exception e){
    e.printStackTrace();
}
 
 
cs


위 예제 처럼 catch(Exception e)에 Exception을 e.printStacktrace() 를 호출 하는 것 보단,

Log.w(TAG, "Application message", e); 를 이용하여 처리하는 것이 Error 관리가 용이하고,

log 필터 시 가독성이 뛰어나다.



1
2
3
4
5
6
try{
    //Exception
}catch(Exception e){
    //e.printStackTrace();
    Log.w(TAG, "something error!!" , e);
}
cs


또한 특정 모듈에서 catch(Exception e)에 발생한 Exception을 re throw 하여 UI 단에서 처리하는 방법도 

좋은 좋은 방법이다.


1
2
3
4
5
6
7
8
9
10
void function() throws Exception {
    try{
    //Exception
    }catch(Exception e) {
        //e.printStackTrace();
        Log.w(TAG, "something error!!" , e);
        new throw Exception("someting error!!", e);
    }    
}
 
cs



마지막으로 try - catch 구문에서 마지막에 finally를 사용하는데,

finally의 경우에는 해당 스택이 종료되어도 마지막에 호출된다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
void function() throws Exception {
    try{
    //Exception
    }catch(Exception e) {
        //e.printStackTrace();
        Log.w(TAG, "something error!!" , e);
        new throw Exception("someting error!!", e);
    }finally{
        System.out.println("called finally");
    }
    System.out.println("function end");    
}
 
cs



위 예제의 함수 function()은 Exception이 발생하였을 때 new throw Exception("someting error!!", e);

종료되어 가장 마지막 줄의 System.out.println("function end"); .은 호출되지 않는다.

하지만 함수가 종료되어도 finally 구문은 동작 하여 System.out.println("called finally"); 은 호출되게 된다.


하지만 finally구문은 System.exit()가 호출되어 프로그램이 종료되거나, JVM이 Crash로 인해 종료되면 호출되지 않는다.

반응형