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
Replay: real traced execution (multi-file project)
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));
}
call ← safeDivide(10, 2)
10void main() {11 print(safeDivide(10, 2));12 print(safeDivide(10, 0));values this stepsafeDivide(10, 2)callreturn value ← 5
3 if (b == 0) throw FormatException('divide by zero');4 return a ~/ b;5} catch (e) {values this step5return value10a2bprint(safeDivide(10, 2));
10void main() {11 print(safeDivide(10, 2));12 print(safeDivide(10, 0));output5call ← safeDivide(10, 0)
11 print(safeDivide(10, 2));12 print(safeDivide(10, 0));13}values this stepsafeDivide(10, 0)callthrows ← FormatException('divide by zero')
2try {3 if (b == 0) throw FormatException('divide by zero');4 return a ~/ b;values this stepFormatException('divide by zero')throws0breturn value ← 0
5} catch (e) {6 return 0;7}values this step0return valueprint(safeDivide(10, 0));
11 print(safeDivide(10, 2));12 print(safeDivide(10, 0));13}output0
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.