try ~ catch란? "예방", "방어"의 의미로 볼 수 있다.

 

코드를 작성하다보면 정말 다양한 경우의 수를 만나게 된다.

내가 받아야하는 결과값이 모호한 경우 try ~ catch문을 사용한다.

 

기본 사용법

  try {
    int result = int.parse("Occur Error!");
    print("result:$result");
  } catch (e, stackTrace) {
    print("Error:$e");
  }

 

String타입을 int타입으로 변환(형변환)하려는 코드이다.

에러메시지는 다음과 같이 표출된다.

Error:FormatException: Occur Error!

 

 

에러 추적 하는법

catch안에는 사실 두 개의 파라메터가 존재하다.

e만 있는 것이 아닌 stackTrace도 정의해주면 에러가 어떻게 발생되었는지 그 과정을 볼 수 있다.

  try {
    int result = int.parse("Occur Error!");
    print("result:$result");
  } catch (e, stackTrace) {
    print("Error:$e");
    print("StackTrace:$stackTrace");
  }

 

 

 

'on'키워드 사용

Error의 메시지를 보면 FormatException이 발생한 것을 알 수 있다.

상황에 따라서 여러 예외상황이 발생했을때 다르게 분기처리를 해주어야 하는 경우도 있을 것이다.

그런 경우를 위해 'on' 키워드를 사용해서 예외를 분리한다.

  try {
    int result = int.parse("Occur Error!");
  } on FormatException {
    print("Implement.. FormatException");
  } catch (e) {
    print("Error:$e");
  }
}

 

if문처럼 조건이 맞으면 다음 catch문은 읽지 않기 때문에 상황에따라 적절하게 구현하면 될 것이다.

추가로 on FormatException이라고 분리해준뒤 catch문을 사용해서 어떠한 에러인지 왜 발생했는지 추적할 수 있다.

  try {
    int result = int.parse("Occur Error!");
  } on FormatException catch(e, stackTrace){
    print("Implement.. FormatException.. Error:$e");
  } catch (e) {
    print("Error:$e");
  }

 

 

finally키워드

try ~ catch문을 사용한 이후 어떠한 작업이 이루어져도 무조건적으로 실행해주는 동작을 뜻한다.

에러가 발생해도 무조건 실행해주는 동작, 이라고 이해하면 쉽다.(당연히 정상적인 동작이 되어도 실행해준다)

  try {
    int result = int.parse("Occur Error!");
  } on FormatException catch(e, stackTrace){
    print("Implement.. FormatException.. Error:$e");
  } catch (e) {
    print("Error:$e");
  } finally{
    print("Finally Exit Casting Operate String to Integer..");
  }

 

 

rethrow 고급 문법

try ~ catch내부에 또다른 try ~ catch가 있는 경우 rethrow키워드를 사용해서 상위 try ~ catch문에 Exception을 전달하는 것이다. 예외를 발생하는 것을 상위 try ~ catch문으로 다시 던지는 것이라고 보면 된다.

 

+ Recent posts