How to achieve exception chaining in Dart?

Viewed 117

In Java, I can achieve exception chaining by passing another exception to the new exception like this:

try {
  doSomething();
} catch (Exception1 ex) {
  throw new Exception2("Got exception1 while doing the thing", ex);
}

I would like to achieve a similar result in Dart. How can I do that?

1 Answers

One way to do it is like this:

void main(){
  try {
    try {
      throw 'exception 1';
    } catch (e) {
      throw LinkedException('exception 2',e);
    }
  } catch (e) {
    throw LinkedException('exception 3',e);
  }
}

class LinkedException implements Exception {
  final String cause;
  final exception;

  LinkedException(this.cause,[this.exception]);

  @override
  String toString() => '$cause <- $exception';
}

If you catch the third exception and print it, you would get something like this:

exception 3 <- exception 2 <- exception 1

Dartpad Runnable example: https://dartpad.dev/4000ed0f1e170615923f6c1e7f5f468a

Related