How to throw an exception in Dart

How to throw an exception in Dart :

We can throw an exception manually in Dart. Dart has a couple of predefined Exceptions and these are thrown automatically on any unexpected result. You can raise predefined exceptions, custom exceptions or arbitrary objects. In this post, I will quickly show you how to throw an exception in dart with examples.

Throw predefined exceptions :

main() {  
  throw FormatException("Please enter a valid format.");
}

This will throw one FormatException like below :

Unhandled exception:
FormatException: Please enter a valid format.
#0      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:2:3)
#1      _startIsolate.< anonymous closure=""> (dart:isolate-patch/isolate_patch.dart:305:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

You can wrap this code inside a try-catch block.

Throw arbitrary object :

main() {  
  throw "Not implemented exception";
}

This is another way to throw an exception. Output :

Unhandled exception:
Not implemented exception
#0      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:2:3)
#1      _startIsolate.< anonymous closure=""> (dart:isolate-patch/isolate_patch.dart:305:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

rethrow :

If you handle an exception with a catch block, it doesn’t throw the exception, but you can throw it using rethrow even with a catch block.

main() {
  try {
    throw "Not implemented exception";
  } catch (e) {
    print("Exception...");
  }
}

This program will result :

Exception...

But if you add one rethrow after the print statement,

main() {
  try {
    throw "Not implemented exception";
  } catch (e) {
    print("Exception...");
    rethrow;
  }
}

It will throw the exception :

Exception...
Unhandled exception:
Not implemented exception
#0      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:3:5)
#1      _startIsolate.< anonymous closure=""> (dart:isolate-patch/isolate_patch.dart:305:19)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)