Skip to content

Disallowing throwing expressions that aren't assignable to Error #33596

@Ginden

Description

@Ginden

Search Terms

throw, throwing non-error

Suggestion

Add typechecking to throw statement, allowing it to only throw Errors and anys.

Code currently allowed, but with strong potential for bugs:

throw null;
throw undefined;
throw 'foobar';
throw ''; 
throw 42;
throw {foo: 'bar'};
throw potentiallyNullable; // with –strictNullChecks

After implementing this feature request, such code wouldn't be allowed.

Use Cases

Even if it's possible to throw non-errors in JavaScript code, it's extremely confusing and hard to debug. Failing to properly handle such cases happened even to Mozilla.

Examples

Forbidden code:

throw null;
throw undefined;
throw 'foobar';
throw 42;
throw {foo: 'bar'};
throw potentiallyNullable; // with –strictNullChecks

Allowed:

throw new Error();
throw null as any;

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code - it can break existing TypeScript code.
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions