Error Handling
Guard Clause
Guard clauses return early for invalid or missing input, leaving the main path less nested.
Program
Play the program to classify a score, then select a missing value to follow the first guard.
guard_clause.dart
Replay: real traced execution (multi-file project)
String classify(int? score) {
if (score == null) return 'missing';
if (score < 60) return 'retry';
return 'pass';
}
void main() {
int? score = 85;
var label = classify(score);
print(label);
}
String classify(int? score) {
if (score == null) return 'missing';
if (score < 60) return 'retry';
return 'pass';
}
void main() {
int? score = null;
var label = classify(score);
print(label);
}
score ← 85
7void main() {8 int? score = 85;9 var label = classify(score);values this step85scorecall ← classify(85)
8int? score = 85;9var label = classify(score);10print(label);values this stepclassify(85)call85scorescore == null ← false
1String classify(int? score) {2 if (score == null) return 'missing';3 if (score < 60) return 'retry';values this stepfalsescore == null85scorescore < 60 ← false
2if (score == null) return 'missing';3if (score < 60) return 'retry';4return 'pass';values this stepfalsescore < 6085scorereturn value ← pass
3 if (score < 60) return 'retry';4 return 'pass';5}values this steppassreturn valuelabel ← pass
8int? score = 85;9var label = classify(score);10print(label);values this steppasslabelprint(label);
9 var label = classify(score);10 print(label);11}outputpassvalues this steppasslabel
score ← null
7void main() {8 int? score = null;9 var label = classify(score);values this stepnullscorecall ← classify(null)
8int? score = null;9var label = classify(score);10print(label);values this stepclassify(null)callnullscorereturn value ← missing
1String classify(int? score) {2 if (score == null) return 'missing';3 if (score < 60) return 'retry';values this stepmissingreturn valuenullscorelabel ← missing
8int? score = null;9var label = classify(score);10print(label);values this stepmissinglabelprint(label);
9 var label = classify(score);10 print(label);11}outputmissingvalues this stepmissinglabel
guard clause
A guard handles an edge case and exits early.
nullable input
`int? score` allows the missing-value case.
flat main path
After guards, the remaining code is the normal case.