1. 예외 처리
- 예외(Exception): 실행 중 발생하는 비정상 상황. 처리하지 않으면 프로그램이 종료되지만, try-catch로 처리하면 정상 실행을 이어갈 수 있다.
- 예외 종류
- Dart가 미리 정의한 예외 (ex: FormatException, IOException, TimeoutException)
- 사용자가 정의하는 예외 (Exception 클래스를 상속해서 구현)
class AgeException implements Exception {
final String message;
AgeException(this.message);
@override
String toString() => message;
}
- 예외 처리 구문
try {
int result = int.parse("abc");
} on FormatException catch (e) {
print("형식 오류: $e");
} catch (e) {
print("기타 오류: $e");
} finally {
print("예외 처리 종료");
}
- throw로 의도적으로 예외를 발생시킬 수 있다.
2. 라이브러리
- 라이브러리: 자주 사용하는 기능을 미리 작성해 둔 코드 집합.
→ 효율성, 재사용성, 가독성 향상. - 종류
- Dart SDK 기본 라이브러리: dart:core, dart:async, dart:math, dart:io 등
- 외부 라이브러리: pub.dev에서 제공 (ex : http, intl, shared_preferences)
- 사용 방법
import 'dart:math';
import 'package:http/http.dart' as http;
- 선택적 가져오기
- show → 필요한 기능만
- hide → 특정 기능 제외
- deferred as → 지연 로딩 (필요할 때만 불러오기)
import 'package:greetings/hello.dart' deferred as hello;
Future<void> greet() async {
await hello.loadLibrary();
hello.printGreeting();
}
3. 비동기 프로그래밍
- 동기 방식: 작업이 끝날 때까지 기다림 → 긴 작업에서는 비효율적.
- 비동기 방식: 기다리지 않고 다른 작업을 수행, 결과는 미래에 반환.
- Dart의 대표 클래스
- Future: 단일 비동기 결과
Future<String> getMessage() async {
await Future.delayed(Duration(seconds: 2));
return '2초 후 메시지 도착!';
}
void main() async {
print(await getMessage());
}
- Stream: 여러 개의 비동기 결과 (데이터 흐름)
Stream<int> countdown(int n) async* {
for (var i = n; i >= 0; i--) {
yield i;
await Future.delayed(Duration(seconds: 1));
}
}
void main() {
countdown(3).listen((value) => print(value));
}
예외 처리를 통해 프로그램을 안전하게 유지할 수 있고, 라이브러리를 활용하면 효율적이고 재사용성 높은 코드를 작성할 수 있다. Dart의 비동기 프로그래밍(Future & Stream)은 시간이 오래 걸리는 작업을 다룰 때 필수적이다.
어제 오늘 했던 복습세션에서 진행한 내용들은 모두 우리가 실제로 프로그래밍할 때 실질적이고 필요한 내용들이였다. 실제 프로그램의 안정성과 효율성을 올려주는 내용들이기 때문에 꼭 깊게 공부 할 필요가 있겠다.