Skip to content

Make Object.toString @mustBeOverriden in Exception and Error #59729

Open
@gaaclarke

Description

@gaaclarke

The problem

I was using the package flame_tiled which parses xml files generated by the Tiled app and draws the results. I was getting an exception when parsing the file, but the log to console and to the screen only read "Instance of 'Parsing Exception'". With the stacktrace I was able to find the line of code generating the exception and see the exception class. I noticed that it is taking in data related to the failure, but since it never overrode Object.toString that information was never reported back to me.

By hacking the code in my ~/.pub-cache I was able to edit the code and debug the problem.

code:

part of tiled;

class ParsingException implements Exception {
  final String name;
  final String? valueFound;
  final String reason;
  ParsingException(this.name, this.valueFound, this.reason);
}

screenshot:
Screenshot 2024-12-16 at 9 46 57 AM

Proposal

I think it is an error to subclass Error or Exception and not override Object.toString. If someone wants the Object.toString they should explicitly have to opt into that, instead of getting it implicitly. We should have an annotation that forces subclasses to override toString for this case.

abstract interface class Exception {
  @mustBeOverriden
  String toString();
}

Alternatives considered

Here are some thoughts:

  1. Migrate people from using Object.toString by introducing a new abstract method, like String what(). There is too much written code that relies on using Object.toString.
  2. Make Object.toString abstract. This is obviously super breaking.
  3. Leave it as is. This creates scenarios like the above that are unhelpful for users, good implementations of Exception and Error will override toString anyways. It will only be breaking poorly written subclasses.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.type-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions