Dart
Dart : Exceptions
iosroid
2019. 9. 20. 16:32
Dart Exceptions
Throw
throw FormatException('Expected at least 1 section');
// throw arbitarary objects
throw 'Out of llamas!';
void distanceTo(Point other) => throw UnimplementedError();
Catch
try {
breedMoreLlamas();
} on OutOfLlamasException {
buyMoreLlamas();
}
// multiple catch clauses
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');
}
// one or two parameters
try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
// rethrow to caller
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
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.
}
library Error and Exception
- DeferredLoadException
- FormatException
- IntegerDivisionByZeroException
- IOException
- IsolateSpawnException
- TimeoutException
- AbstractClassInstantiationError
- ArgumentError
- AssertionError
- AsyncError
- CastError
- ConcurrentModificationError
- CyclicInitializationError
- FallThroughError
- JsonUnsupportedObjectError
- NoSuchMethodError
- NullThrownError
- OutOfMemoryError
- RemoteError
- StackOverflowError
- StateError
- UnimplementedError
- UnsupportedError