How to create a custom exception and handle it in dart

Question

Asked by Vickyonit on November 27, 2012 (source).

I have written this code to test how custom exceptions are working in the dart.

I'm not getting the desired output could someone explain to me how to handle it??

void main() 
{   
  try
  {
    throwException();
  }
  on customException
  {
    print("custom exception is been obtained");
  }
  
}

throwException()
{
  throw new customException('This is my first custom exception');
}

Answer

Question answered by Alexandre A (source).

You can look at the Exception part of A Tour of the Dart Language.

The following code works as expected (custom exception has been obtained is displayed in console) :

class CustomException implements Exception {
  String cause;
  CustomException(this.cause);
}

void main() {
  try {
    throwException();
  } on CustomException {
    print("custom exception has been obtained");
  }
}

throwException() {
  throw new CustomException('This is my first custom exception');
}
DART EXCEPTION FLUTTER TRY-CATCH
SHARE: