๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Throwing in Depth

throw can send any value, not just an exception object. A catch block receives the exact value that was thrown.

Throwing a string value

The throw sends a plain string. The catch prints the string itself.

void main() {
  try {
    throw 'Empty name';
  } catch (e) {
    print(e);
  }
}

Throwing a number value

A number can travel the same way. The catch prints it inside a sentence.

void main() {
  try {
    throw 404;
  } catch (e) {
    print('Caught: $e');
  }
}

Rethrow to an outer handler

The inner catch prints its line first. rethrow then sends the same value to the outer catch.

void main() {
  try {
    try {
      throw 'boom';
    } catch (e) {
      print('inner saw $e');
      rethrow;
    }
  } catch (e) {
    print('outer saw $e');
  }
}

A guard clause throws early

The function checks the name before building the greeting. Bad input throws a string and the greeting never runs.

String greet(String name) {
  if (name.isEmpty) {
    throw 'Name is required';
  }
  return 'Hello $name';
}

void main() {
  try {
    print(greet(''));
  } catch (e) {
    print(e);
  }
  print(greet('Ana'));
}

Example

String grade(int score) {
  if (score < 0) {
    throw 'Score cannot be negative';
  }
  if (score >= 50) {
    return 'pass';
  }
  return 'fail';
}

void main() {
  print(grade(80));
  try {
    print(grade(-5));
  } catch (e) {
    print(e);
  }
}

Key points

  • The value after throw can be a string, a number or any other value.
  • A plain catch receives the thrown value exactly as it was sent.
  • rethrow inside a catch sends the same value onward to an outer handler.
  • The inner handler can report the problem before the outer handler deals with it.
  • A guard clause checks input first and throws before the real work starts.

In this example, the first call returns pass and prints it. The second call hits the guard clause, throws a string, and the catch prints that string.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does rethrow do inside a catch block?