Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom exception and handle it in dart

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'); } 
like image 785
Vickyonit Avatar asked Nov 27 '12 08:11

Vickyonit


People also ask

How do you use custom exceptions in Dart?

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.

Which keyword is used to throw a custom exception in Dart?

The throw keyword is used to explicitly raise an exception.

How do you handle exceptions in flutter?

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 ...


2 Answers

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'); } 
like image 119
Alexandre Ardhuin Avatar answered Sep 23 '22 06:09

Alexandre Ardhuin


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"); 
like image 23
Sabrina Avatar answered Sep 23 '22 06:09

Sabrina