본문 바로가기

Flutter

dart(2) - 예외처리

void main(){

  int num1 = 10;
  try{
    print(10~/0);
  }catch(error, stack){
    print(error);
    print(stack);
  }finally{
    print("예외처리 통과");
  }
}

 

에러를 캐치한다.

IntegerDivisionByZeroException
#0      int.~/ (dart:core-patch/integers.dart:30:7)
#1      main (file:///C:/dart_programming2/test.dart:5:13)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:296:19)
#3      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:189:12)

예외처리 통과

finally는 에러의 유무 상관없이 그냥 출력한다.

 

 

 

void main(){

  int num1 = 10;
  try{
    print(10~/0);
  }on UnsupportedError catch(e,s){
    print('~/ 해당 연산자는 0으로 나눌 수 없다');
  }
}
~/ 해당 연산자는 0으로 나눌 수 없다

특정 에러를 지정할 때 on을 쓴다.

 

 

 

void main(){

  int? num;

  try{
    print(num!);
  }on UnsupportedError catch(e,s){
    print('~/ 해당 연산자는 0으로 나눌 수 없다');
  }on TypeError catch(e,s){
    print('Null 값이 참조 되었습니다.');
  }
}
Null 값이 참조 되었습니다.

 

 

 

void main(){

  try{
    throw Exception('Unknown Error');
  }on UnsupportedError catch(e,s){
    print('~/ 해당 연산자는 0으로 나눌 수 없다');
  }on TypeError catch(e,s){
    print('Null 값이 참조 되었습니다.');
  } catch (e,s){
    print('모르는 에러가 발생했습니다.');
  }
}
모르는 에러가 발생했습니다.

throw catch 도 가능

'Flutter' 카테고리의 다른 글

플러터 위젯 - 예시  (0) 2024.03.13
Flutter 위젯  (0) 2024.03.12
dart(3) - 비동기 프로그래밍  (0) 2024.03.11
Flutter 설치  (0) 2024.03.10
Dart 기초  (0) 2024.03.09