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));
}
  1. call ← safeDivide(10, 2)

    10void main() {11  print(safeDivide(10, 2));12  print(safeDivide(10, 0));
    values this stepsafeDivide(10, 2)call
  2. return value ← 5

    3  if (b == 0) throw FormatException('divide by zero');4  return a ~/ b;5} catch (e) {
    values this step5return value10a2b
  3. print(safeDivide(10, 2));

    10void main() {11  print(safeDivide(10, 2));12  print(safeDivide(10, 0));
    output5
  4. call ← safeDivide(10, 0)

    11  print(safeDivide(10, 2));12  print(safeDivide(10, 0));13}
    values this stepsafeDivide(10, 0)call
  5. throws ← FormatException('divide by zero')

    2try {3  if (b == 0) throw FormatException('divide by zero');4  return a ~/ b;
    values this stepFormatException('divide by zero')throws0b
  6. return value ← 0

    5} catch (e) {6  return 0;7}
    values this step0return value
  7. print(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.