Dart : The method 'errMsg' isn't defined for the class 'Object'

31 Views Asked by At
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

There are 2 best solutions below

1
Dhafin Rayhan On BEST ANSWER

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());
}
1
Sreelal TS On

The catch block in your code basically catches all unexpected exceptions that may occur in your code. And that's exactly why the e has the type Object instead of AmtException.

Solution 1

You can specifically catch the AmtException as follows.

  try {
    // your code
  } on AmtException catch (e) {
    print(e.errMsg());
  }

Solution 2

You can catch all exception as in your code, and double check if the e is an instance of the AmtException to continue with the errMsg() call. You can use the following code for this behaviour:

  try {
    // your code
  } catch (e) {
    if (e is AmtException) {
      print(e.errMsg());
    }

    // Handle other exceptions (if needed)
    // ...
  }