Reputation: 28916
Exception
class looks like:
abstract class Exception {
factory Exception([var message]) => _Exception(message);
}
_Exception
class is the implementation of it. As you can see there are no fields or functions declared in this class other than a factory constructor, so what's the significance of having such classes?
Upvotes: 0
Views: 39
Reputation: 71693
It's like a marker interface which tells the reader that a subclass is intended to be used as an exception (thrown in a situation where the user is expected to catch and handle the exceptional situation, rather than an error).
Dart, the language, does not treat Exception
specially. It's completely unnecessary from a technical point of view since all objects can be thrown. Making your class implement Exception
signifies that it's purpose is to be thrown, even though it is not an Error
, but you should see it as documentation, not something your program can meaningfully use.
Exceptions, unlike Error
s, are intended to be caught and handled, just as much as a return value is. An exception should contain enough information to make the receiver able to do something meaningful.
Because of that, you should never throw a plain Exception
in production code (so the constructor is really deprecated except during development, until you have created a proper exception class).
Similarly, you should never catch a plain Exception
(no on Exception catch (e) {...}
) because then you are not handling the actual problem. If you just want to catch anything, use on Object
, because code can throw any class, and not all exception classes need to implement Exception
.
Upvotes: 2