class AmtException implements Exception {
String errMsg() => 'Amount should not be less than zero';
}
void main() {
try {
var amt = -1;
if (amt < 0) {
throw AmtException();
}
} catch (e) {
print(e.errMsg());
}
}
I am trying to create custom exception and throw the object of custom exception class. But when I am trying to call the method of custom class exception.
Error
dart/exceptions.dart:81:11: Error: The method ‘errMsg’ isn’t defined for the class ‘Object’.
- ‘Object’ is from ‘dart:core’.
Try correcting the name to the name of an existing method, or defining a method named ‘errMsg’.
error.errMsg();
2
Answers
When you use
catch (e)
, it means you’re catching any errors, so the type fore
isObject
.If you want to catch a specific error, use the
on NameOfTheException catch (e)
syntax:The
catch
block in your code basically catches all unexpected exceptions that may occur in your code. And that’s exactly why thee
has the typeObject
instead ofAmtException
.Solution 1
You can specifically catch the AmtException as follows.
Solution 2
You can catch all exception as in your code, and double check if the
e
is an instance of theAmtException
to continue with theerrMsg()
call. You can use the following code for this behaviour: