25

I keep getting an error when I try to extend the Exception class and can't figure out why. Here is the code for my custom exception:

class MyException extends Exception {
  String msg;
  MyException(this.msg);
  String toString() => 'FooException: $msg';
}

The error resolves around the constructor. It complains that "The generative constructor 'Exception([dynamic message]) -> Exception' expected, but factory found". How do I fix this?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • You cannot extend a class defining just a factory constructor. http://stackoverflow.com/questions/18564676/extending-a-class-with-only-one-factory-constructor – user7610 Jan 31 '14 at 14:08

2 Answers2

53

You have it almost right. You need to implement Exception rather than extend it. This should work:

class MyException implements Exception {
  final String msg;
  const MyException(this.msg);
  String toString() => 'FooException: $msg';
}

You don't have to make msg final or the constructor const, but you can. Here is an example of an implementation of the Exception class (from the dart:core library):

class FormatException implements Exception {
  /**
   * A message describing the format error.
   */
  final String message;

  /**
   * Creates a new FormatException with an optional error [message].
   */
  const FormatException([this.message = ""]);

  String toString() => "FormatException: $message";
}
Shailen Tuli
  • 13,815
  • 5
  • 40
  • 51
4

I'd like to add to the other answer: more than a message string, it'd be useful to have a type or code so the invoker can decide what to do based on the exception type. For example:

enum NfcErrorType { communication, parse, timeout, mismatch }

class NfcException implements Exception {
  final NfcErrorType type;

  NfcException(this.type);

  @override
  String toString() {
    return 'NfcException: $type';
  }
}

Then you can throw like:

throw NfcException(NfcErrorType.parse);

And the invoker can catch this way:

try {
  // ...
} on NfcException catch (err) {
  switch(err.type) {
    case NfcErrorType.parse:
      // do something
      break;
    case NfcErrorType.communication:
      // do something different
      break;
    // .... other cases

  }
} catch(err) {
  // handle some other way...
}
maganap
  • 2,414
  • 21
  • 24