Skip to content

Can an NNBD library catch dynamic? #916

@munificent

Description

@munificent

As I was migrating language_2/exception/try_catch_optimized5_test.dart, I ran into an interesting failure. Given:

main() {
  try {
    throw "ok";
  } on dynamic catch (error) {
    print(error);
  }
}

It runs fine in the VM:

$ dart --null-safety --enable-experiment=non-nullable temp.dart
ok

But analyzer does not like it:

$ dartanalyzer --enable-experiment=non-nullable temp.dart
Analyzing temp.dart...
  error • A nullable type can't be used in an 'on' clause because it isn't valid to throw 'null'. • temp.dart:4:8 • nullable_type_in_catch_clause
1 error found.

I don't see anything in the NNBD spec related to catching non-nullable types so I don't know which tool is behavior correctly. My hunch is that we probably do want to treat dynamic specially and allow that in a catch clause even though it's technically nullable?

A related question is around type parameters:

main<T>() {
  try {
    throw "ok";
  } on T catch (error) {
    print(error);
  }
}

Analyzer currently considers that an error, but does allow:

main<T extends Object>() {
  try {
    throw "ok";
  } on T catch (error) {
    print(error);
  }
}

cc @stereotype441 @scheglov @johnniwinther

Metadata

Metadata

Assignees

No one assigned

    Labels

    nnbdNNBD related issuesquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions