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'.
When you use catch (e)
, it means you're catching any errors, so the type for e
is Object
.
If you want to catch a specific error, use the on NameOfTheException catch (e)
syntax:
try {
throw AmtException();
} on AmtException catch (e) {
// Now `e` is an `AmtException`
print(e.errMsg());
}