티스토리 뷰

Dart에서 try catch 구분 등을 사용하여 예외를 처리하는 방법입니다.

Dart를 포함하여, Java 등 대부분의 언어에서 프로그램 실행 중 Exception이 발생합니다.

기본적으로 Exception을 처리하지 않으면 프로그램이 종료됩니다.

Dart에서는 try catch나 try on 구문을 사용하여 예외를 처리할 수 있습니다.

1. try catch

아래 예제의 try 구문에서 예외가 발생했을 때, catch에서 예외가 처리됩니다.

catch (e) 처럼 Exception 종류가 명시되지 않았기 때문에 모든 예외를 처리할 수 있습니다.

String str = "abc12";  

int n;  
try {  
    n = int.parse(str);  
    print(n);  
} catch (e) {  
    n = -1;  
    print("error: $e");  
}

2. try on

try on Exception은 특정 예외만 처리할 수 있습니다.

`try on FormatException`은 FormatException 예외만 처리할 수 있으며, 다른 Exception 발생 시 프로그램이 종료됩니다.

    String str = "abc12";

    int n;
    try {
        n = int.parse(str);
        print(n);
    } on FormatException {
        n = -1;
        print("set n to -1");
    }

3. try on Exception catch

"try on Exception catch (e)"는 FormatException만 처리할 수 있고, catch 구문으로 Exception 객체인 e가 전달됩니다.

    String str = "12abc";

    int n;
    try {
        n = int.parse(str);
        print(n);
    } on FormatException catch (e) {
        n = -1;
        print("error: $e");
    }

4. try on/catch finally

finally 구문이 추가되면, try on/catch에서 예외처리가 수행된 이후에, finally 구문이 항상 실행됩니다.

int n;  
try {  
    print("try");  
    n = 0;  
} finally {  
    print("finally");  
}  

아래 코드를 실행해보면, 호출 순서를 눈으로 확인할 수 있습니다.

String str = "abc12";  

int n;  
try {  
    n = int.parse(str);  
    print(n);  
} on FormatException catch (e) {  
    n = -1;  
    print("error: $e");  
} finally {  
    print("finally");  
}