Skip to content

Instantly share code, notes, and snippets.

@RedBrogdon
Last active March 22, 2022 15:22
Show Gist options
  • Save RedBrogdon/b272fbb6689c623f9dfb2258e19088a8 to your computer and use it in GitHub Desktop.
Save RedBrogdon/b272fbb6689c623f9dfb2258e19088a8 to your computer and use it in GitHub Desktop.
Snippet 7: Promotion with exceptions
// Promotion works with exceptions as well
// as return statements. Try a null check
// that throws an `Exception` instead of
// returning zero.
int getLength(String? str) {
// Try throwing here if `str` is null.
return str.length;
}
void main() {
print(getLength(null));
}
@xordox
Copy link

xordox commented Mar 22, 2022

int? getLength(String? str) {
// Try throwing an exception here if str is null.

try{
return str!.length;
}on Exception catch (e) {
throw('$e.runtimeType.toString() $e.message');
}
}

void main() {
print(getLength(null));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment