Async and Practical
Try/Catch
Fallback Value
try { ... } catch (e) { ... } runs the block and recovers when an exception is thrown.
Program
Play the program to safely divide by zero with a fallback.
exceptions.dart
int safeDivide(int a, int b) {
try {
if (b == 0) throw FormatException('divide by zero');
return a ~/ b;
} catch (e) {
return 0;
}
}
void main() {
print(safeDivide(10, 2));
print(safeDivide(10, 0));
}
try/catch
`catch (e)` binds the thrown value so the program can recover.
throw
`throw FormatException(...)` raises an exception.
fallback
Returning a default keeps the caller working.