예외와 복구
Coddy의 C# 개발자를 위한 Dart 코스 레슨. 48개 중 25번째.
C#의 catch 타입 필터와 Dart의 on 절은 예상되는 예외 유형을 선택합니다. Dart의 catch는 두 번째 매개변수로 스택 추적도 받을 수 있습니다. 어느 언어에서도 모든 오류를 잡는 것은 좋은 복구 방안이 아닙니다.
on으로 예외 유형을 선택하고, catch로 발생한 객체와 선택적으로 스택 추적을 바인딩하세요. finally는 정상적으로 완료될 때와 일반적인 스택 풀기 과정에서 정리 작업을 수행합니다. 프로그래밍 오류를 숨기지 않으면서 예상되는 실패를 처리하세요.
완전한 C# 프로그램:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(){try{throw new FormatException("bad");}catch(FormatException){Console.WriteLine("format");}finally{Console.WriteLine("cleanup");}}
}
완전한 Dart 프로그램:
void main(){try{throw FormatException('bad');}on FormatException{print('format');}finally{print('cleanup');}}챌린지
쉬움divide(int a,int b)를 구현하세요. 제수가 0이면 ArgumentError를 발생시키고, 나눗셈의 나머지가 0이 아니면 StateError를 발생시키며, 그 외에는 정수 몫을 반환하세요. 입력에는 -100부터 100까지의 정수 두 개가 포함됩니다. 래퍼는 zero, fraction 또는 몫을 출력합니다.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 출력을 반환하며, 잠긴 드라이버는 공개 API를 독립적으로 테스트하고 결과를 줄바꿈 하나와 함께 출력합니다.
코드는 functions.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(divide(15,3)==5);var caught=false;try{divide(1,0);}on ArgumentError{caught=true;}check(caught);
stdout.writeln(solve(input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러