Dart

[Dart] 예외 처리 (Error Handling)

Meezzi 2025. 3. 17. 22:46
728x90

1. 예외 (Exception)

 

예외는 프로그램이 실행되는 동안 발생할 수 있는 예외적인 상황입니다.

예외는 프로그래머가 예측 가능하고, 적절히 처리할 수 있습니다.

 

예외를 처리해 주지 않으면 프로그램이 종료되지만,

이를 try-catch로 처리해 주면 프로그램이 정상적으로 실행됩니다.

 

Dart에서는 모든 예외가 Exception 클래스를 기반으로 구현됩니다.

 

 

2. 예외 처리

1) try ~ catch

try의 코드 블록 실행 중에 예외가 발생하면

try 코드 블록의 예외 발생 후의 코드들은 실행되지 않고 catch문으로 넘어갑니다.

 

즉, try의 코드 블록에는 예외가 발생할 수 있는 코드가,

catch 코드 블록에는 예외가 발생했을 때 실행되어야 할 코드가 있어야 합니다.

 

void main() {
  try {
    int number = int.parse("hello"); 	// "hello"를 숫자로 변환하려고 하면 예외 발생
    print("입력한 숫자: $number");
  } catch (e) {
    print("$e 오류가 발생하였습니다.");
  }
}

// FormatException: hello 오류가 발생하였습니다.

 

 

2) on

on 키워드는 발생할 수 있는 예외 중 특정 예외만 처리할 수 있습니다.

 

1번의 try ~ catch에서는 정확히 어떤 예외가 발생했는지 알 수 없어 전체 예외에 대한 메시지를 표시했지만,

on키워드는 예외 타입이 FormatException에 특정되어 '숫자가 아닌 값을 입력했습니다.'라는 메세지를 표시할 수 있습니다.

 

void main() {
  try {
    int number = int.parse("hello");
    print("입력한 숫자: $number");
  } on FormatException {
    print("숫자가 아닌 값을 입력했습니다.");
  }
}

// 숫자가 아닌 값을 입력했습니다.

 

 

3) finally

finally 블록은 예외 발생 여부와 관계없이 항상 실행됩니다.

 

try, catch를 모두 거친 후에 실행되며, 예외 처리 구문을 작성할 때 굳이 넣지 않아도 됩니다.

void main() {
  try {
    int number = int.parse("hello");
    print("입력한 숫자: $number");
  } on FormatException {
    print("숫자가 아닌 값을 입력했습니다.");
  } finally {
    print("고생하셨습니다.");
  }
}

// 숫자가 아닌 값을 입력했습니다.
// 고생하셨습니다.

 

 

 

4) throw

throw는 예외를 의도적으로 발생시키는 키워드입니다.

이때, 던진다(throw)는 의미는 예외를 발생시켜 호출한 쪽으로 던져 처리한다는 의미입니다.

 

즉, throw는 이 코드에서 문제가 발생했으니, 상위 코드(호출한 곳)에서 처리하라는 의미입니다.

 

void checkNumber(int number) {
  if (number < 0) {
    throw Exception("음수는 허용되지 않습니다!");
  }
  print("정상적인 숫자: $number");
}

void main() {
  try {
    checkNumber(-5); 		// 음수 입력
  } catch (e) {
    print("오류 처리: $e");
  }
}

// 오류 처리: Exception: 음수는 허용되지 않습니다!

 

checkNumber 함수에서 예외를 던지면,

checkNumber를 호출한 main함수에서 이를 catch로 받아 처리합니다.

 

 

 

3. 예외 종류

1) Dart가 미리 정의해 둔 예외

예외명 설명
DefferedLoadException 필요한 시점에 로드되도록 설정한 라이브러리가 로드되지 못 했을 때 발생
FormatException 잘못된 형식의 데이터를 변환할 때 발생 
IOException 입출력 관련 작업 중 발생
OSError 운영체제 관련해서 발생
TimeoutException 시간이 초과되었을 때 발생
HttpException HTTP 요청 중 오류 발생

 

 

2) 사용자 정의 예외

Dart에서 기본 제공되는 예외 외에도 개발자가 직접 예외 클래스를 정의할 수 있습니다.

 

사용자 정의 예외를 만들면 더 직관적이고 의미 있는 에러 메시지를 제공할 수 있어 코드의 가독성이 좋아집니다.

 

 

나이 제한을 검사하고, 조건을 만족하지 않으면 예외를 발생시키는 처리를 해보겠습니다.

 

사용자 정의 예외 처리를 하기 위해서는 먼저 예외 클래스를 정의해야 합니다.

class AgeRestrictionException implements Exception {
  final String message;
  AgeRestrictionException(this.message);

  @override
  String toString() => "AgeRestrictionException: $message";
}

 

예외는 모두 Exception 클래스를 구현한다 하였습니다.

사용자 정의 예외도 implements Exception을 사용하여 예외 클래스를 만듭니다.

 

예외 메시지를 저장하고,

toString()을 오버라이딩하여 예외 발생 시 어떤 이유로 발생했는지 설명합니다.

 

void main() {
  try {
    checkAge(16); 			// 16세는 미성년자
  } catch (e) {
    print(e);
  }
}

void checkAge(int age) {
  if (age < 18) {
    throw AgeRestrictionException("미성년자는 입장할 수 없습니다!");
  } else {
    print("입장 가능!");
  }
}

// AgeRestrictionException: 미성년자는 입장할 수 없습니다!

 

checkage는 age를 입력받아 나이가 18세 이상인지 검사하는 함수입니다.

만약, 나이가 18세 미만이면 AgeRestrictionException을 발생시킵니다.

 

 

 

 

 

4. 참고 자료

 

https://dart.dev/language/error-handling

 

Error handling

Learn about handling errors and exceptions in Dart.

dart.dev

 

https://api.dart.dev/stable/latest/dart-core/index.html#exceptions

 

dart:core library - Dart API

dart:core library Built-in types, collections, and other core functionality for every Dart program. This library is automatically imported. Some classes in this library, such as String and num, support Dart's built-in data types. Other classes, such as Lis

api.dart.dev

 

https://stackoverflow.com/questions/21096470/extending-the-exception-class-in-dart

 

Extending the Exception class in Dart

I keep getting an error when I try to extend the Exception class and can't figure out why. Here is the code for my custom exception: class MyException extends Exception { String msg; MyException(

stackoverflow.com

 

728x90