Skip to content

Resolve typing treatment of throw/catch with NNBD #385

@leafpetersen

Description

@leafpetersen

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 null to be thrown?
  • Should we allow potentially nullable things to be thrown?
  • Should we allow the on clause to 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:

  1. 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 the on clause.
  • You can throw something of potentially nullable type by casting it to Object
  • You can catch something of potentially nullable type
  1. 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 the on clause.
  • 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 an is check
  1. Make throwing null not an error, allow throwing potentially nullable types, allowing potentially nullable types in the on clause.
  • 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?

cc @lrhn @munificent @eernstg @stereotype441

Metadata

Metadata

Assignees

Labels

nnbdNNBD related issues

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions