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'); }
An exception usually has an error message and therefore the custom exception class should be able to return an error message. You can create a method with any name for returning the error message, but this tutorial uses toString() which is the same name used in Dart's Exception class.
The throw keyword is used to explicitly raise an exception.
In order to catch all the exceptions in a block of code you wrap the code in try block and use multiple on-catch instructions to handle some specific exceptions, then use catch to handle all other unexpected exceptions, and finally use finally to run the code that should be invoked after the code in try block and in ...
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'); }
You don't need an Exception class if you don't care about the type of Exception. Simply fire an exception like this:
throw ("This is my first general exception");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With