250x250
반응형
05-12 07:02
Today
Total
«   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
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[Dart] Exceptions(예외 처리) 본문

CS(컴퓨터 과학)/Dart

[Dart] Exceptions(예외 처리)

billnjoyce 2020. 8. 20. 16:01
728x90
반응형
Dart 언어에서의 Exceptions(예외 처리)에 대하여 살펴봅니다.

 

 

#. 구독 대상

  • Dart 언어를 처음 접하시면서 공부해보고 싶으신 분
  • 플러터(Flutter) 개발에 관심이 있어나 해보고 싶으신 분
  • 멀티 플랫폼 모바일 앱 개발을 시작하고 싶으신 분
  • 기타 소프트웨어 개발과 지식에 관심이 있으신 모든 분들

 

 


 

Exceptions

Dart 언어에서도 Java나 다른 언어들과 같이 예외를 throw하고 catch 할 수 있습니다.

 

예외는 예상치 못한 일이 발생했음을 나타내는 오류로서 예외가 포착되지 않으면 예외를 발생시킨 격리(isolate)가 일시 중단되며 일반적으로 격리 및 해당 프로그램이 종료됩니다. 

 

Java와 달리 Dart의 모든 예외는 확인되지 않은 예외입니다. 따라서 메서드는 throw 할 수있는 예외를 선언하지 않으며 예외를 catch 할 필요가 없습니다. 

 

Dart는 예외 및 오류 유형뿐만 아니라 수많은 미리 정의 된 하위 유형을 제공합니다. 물론, 자신의 예외를 정의 할 수 있습니다. 그러나 Dart 프로그램은 Exception 및 Error 객체뿐만 아니라 모든 null이 아닌 객체를 예외로 throw 할 수 있습니다.

 

Error class - dart:core library - Dart API

Error objects thrown in the case of a program failure. An Error object represents a program failure that the programmer should have avoided. Examples include calling a function with invalid arguments, or even with the wrong number of arguments, or calling

api.dart.dev

 

Exception class - dart:core library - Dart API

A marker interface implemented by all core library exceptions. An Exception is intended to convey information to the user about a failure, so that the error can be addressed programmatically. It is intended to be caught, and it should contain useful data f

api.dart.dev

 

 

 


 

 

Try

try 절은 try { } 구문 안에서 특정 에러가 발생하였을때 처리를 해주기 위한 방법입니다.
try의 다양한 사용 방식은 아래와 같이 try-on, try-catch, try-on-catch 등의 구문등을 조합하여 사용할 수 있습니다.

try{
    // code
}
// 예외클래스(Exception) 타입을 지정해야 할 때 사용
try{
    // 예외 발생할 수 도 있는 코드
    // code that might throw an exception
}on 예외클래스{
    // 예외처리를 위한 코드
    // code for handling exception 
}


// (exception object) 객체가 필요할 때 사용
try{
   // 예외 발생할 수 도 있는 코드
   // code that might throw an exception
}catch(e){
   // 예외처리를 위한 코드
   // code for handling exception 
}

// 예외클래스(Exception) 타입을 지정 + e(exception object) 객체가 필요할 때 사용
try{
   // 예외 발생할 수 도 있는 코드
   // code that might throw an exception
}on 예외클래스 catch(e){
   // 예외처리를 위한 코드
   // code for handling exception 
}

 

 


 

 

Throw

throw절을 통하여 예외 상황 발생 시 객체 또는 코드 등을 반환할 수 있습니다.

throw FormatException('Expected at least 1 section');

throw 'Out of llamas!';

void distanceTo(Point other) => throw UnimplementedError();


main(List<String> args) {
  try {
    divide(10, 0);
  } on IntegerDivisionByZeroException {
    print('Division by zero.');
  } catch (e) {
    print(e);
  }
}

// IntegerDivisionByZeroException 객체를 throw
divide(int a, int b) {
  if (b == 0) {
    throw new IntegerDivisionByZeroException();
  }
  return a / b;
}

// Exception 객체를 throw
divide(int a, int b) {
  if (b == 0) {
    throw new Exception('Some other exception.');
  }
  return a / b;
}

 

 

 


 

 

Catch

Catch문을 사용하여 예외(Exception) 발생 시 예외 코드가 프로그램 전체에 전파되는 것을 방지할 수 있습니다.

아래는 다양한 try, catch에 대한 예제 코드입니다.

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
}


try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}


try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}


void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // Runtime error
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}

void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}

 

 


 

 

Finally

예외 발생 여부에 관계없이 일부 코드가 실행되도록 하려면 finally 절을 사용하면 됩니다. 예외(Exception)와 일치하는 catch 절이 없으면 finally 절이 실행 된 후 예외가 전파됩니다.

try {
  breedMoreLlamas();
} finally {
  // Always clean up, even if an exception is thrown.
  cleanLlamaStalls();
}


try {
  breedMoreLlamas();
} catch (e) {
  print('Error: $e'); // Handle the exception first.
} finally {
  cleanLlamaStalls(); // Then clean up.
}

 

 

 


 

 

 

지금까지 Dart 언어에서의 Exceptions(예외 처리)에 대해서 살펴보았습니다.

 

감사합니다.

 

 

 

 

 

 

 

 

 


[참고 자료(References)]

 

[1] A tour of the Dart language : dart.dev/guides/language/language-tour

[2] Dart Exception 예외처리 (try on vs try catch) : velog.io/@adbr/Dart-예외처리-try-on-vs-try-catch

[3] Flutter 조건문, 반복문, 예외처리 : sysocoder.com/flutter-조건문-반복문-예외처리/

[4] Dart (DartLang) Introduction: Exception handling : medium.com/run-dart/dart-dartlang-introduction-exception-handling-f9f088906f7c

[5] Dart Exception 예외처리 (try on vs try catch) : velog.io/@adbr/Dart-예외처리-try-on-vs-try-catch

728x90
반응형

'CS(컴퓨터 과학) > Dart' 카테고리의 다른 글

[Dart] Functions(함수)  (0) 2020.08.20
[Dart] Control flow statements(제어문)  (0) 2020.08.20
[Dart] Operators(연산자)  (0) 2020.08.19
[Dart] Collection : List & Set & Map  (0) 2020.08.19
[Dart] Variables(변수)  (0) 2020.08.19
Comments