-
Notifications
You must be signed in to change notification settings - Fork 228
Description
In comments on the NNBD feature spec the question came up of what errors and warnings to provide on throw catch. Currently, Dart makes it a runtime error to throw null. Apparently the reasoning given at the time was that null would match any catch site, and users were unlikely to be prepared to receive null. With NNBD it's possible to distinguish which catch sites are prepared to accept null, so this reason goes away.
There are three questions we should decide:
- Should we change the semantics to allow
nullto be thrown? - Should we allow potentially nullable things to be thrown?
- Should we allow the
on clauseto specify a potentially nullable type?
If we don't change the semantics to allow null to be thrown, then there is no point in having a nullable type in an on clause. However, if you want to catch something of generic type you're out of luck:
foo<T>(Object o) {
try {
if (o != null) throw o;
} on T catch (e) {
Expect.identical(o, e);
}
}
If we don't change the semantics of throwing null, then it seems somewhat unfriendly to allow the user to throw a nullable type, since it will always be an error if the value is actually null. The same issue with generic types arises, but can be worked around by casting to Object.
The options that seem consistent to me are:
- Leave it as a runtime error to throw
null, make it an error to throw a potentially nullable type, and allow a potentially nullable type in theonclause.
- You can throw something of potentially nullable type by casting it to Object
- You can catch something of potentially nullable type
- Leave it as a runtime error to throw
null, make it an error to throw a potentially nullable type, make it an error to have a potentially nullable type in theonclause.
- You can throw something of potentially nullable type by casting it to Object
- You can't catch something of potentially nullable type: you need to catch
Object?and then rethrow based on anischeck
- Make throwing
nullnot an error, allow throwing potentially nullable types, allowing potentially nullable types in theonclause.
- You can throw something of potentially nullable type.
- You can catch something of potentially nullable type, and it may be null.
The current feature spec specified behavior 2. Should we change this?