Dartコードは、例外をスローしてキャッチできます。Javaとは対照的に、Dartのすべての例外はチェックされていない例外です。メソッドは、スローする可能性のある例外を宣言しません。また、例外をキャッチする必要はありません。
Dartは提供しException
、Error
タイプしますが、null以外のオブジェクトをスローすることは許可されています。
throw Exception('Something bad happened.');
throw 'Waaaaaaah!';
try
例外を処理するときは、、、on
およびcatch
キーワードを使用します。
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
て特定の例外をタイプでフィルタリングし、キーワードを使用catch
して例外オブジェクトへの参照を取得します。
例外を完全に処理できない場合は、rethrow
キーワードを使用して例外を伝播します。
try {
breedMoreLlamas();
} catch (e) {
print('I was just trying to breed llamas!.');
rethrow;
}
例外がスローされるかどうかに関係なくコードを実行するには、次を使用しますfinally
。
try {
breedMoreLlamas();
} catch (e) {
// ... handle exception ...
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
コード例
以下に実装しtryFunction()
ます。信頼できないメソッドを実行してから、次のことを実行する必要があります。
untrustworthy()
をスローする場合は、例外タイプとメッセージを指定してExceptionWithMessage
呼び出します(とを使用してみてください)。logger.logException
on
catch
untrustworthy()
例外をスローする場合は、logger.logException
例外タイプで呼び出します(on
これに使用してみてください)。
- 他のオブジェクトをスローする場合
untrustworthy()
は、例外をキャッチしないでください。
- すべてがキャッチされて処理されたら、呼び出します
logger.doneLogging
(を使用してみてくださいfinally
)。
。
typedef VoidFunction = void Function();
class ExceptionWithMessage {
final String message;
const ExceptionWithMessage(this.message);
}
abstract class Logger {
void logException(Type t, [String msg]);
void doneLogging();
}
void tryFunction(VoidFunction untrustworthy, Logger logger) {
try {
untrustworthy();
} on ExceptionWithMessage catch (e) {
logger.logException(e.runtimeType, e.message);
} on Exception {
logger.logException(Exception);
} finally {
logger.doneLogging();