Dart Error or Exceptions Handling : Errors & Exceptions in Dart | Dart Exceptions Handling in Dart | try and on Clouse

Jeet BhaluJeet Bhalu
2 min read

Error handling :

  • Exceptions :

  • Your Dart code can throw and catch exceptions. Exceptions are errors indicating that something unexpected happened. If the exception isn't caught, the isolate that raised the exception is suspended, and typically the isolate and its program are terminated.

  • In contrast to Java, all of Dart's exceptions are unchecked exceptions. Methods don't declare which exceptions they might throw, and you aren't required to catch any exceptions.

  • Dart provides Exception and Error types, as well as numerous predefined subtypes. You can, of course, define your own exceptions. However, Dart programs can throw any non-null object—not just Exception and Error objects—as an exception.

Throw :

  •   throw FormatException('Expected at least 1 section');
    
  •   throw 'Out of llamas!';
    
  • Because throwing an exception is an expression, you can throw exceptions in => statements, as well as anywhere else that allows expressions:

  •   void distanceTo(Point other) => throw UnimplementedError();
    

Try - Catch :

  • Catching, or capturing, an exception stops the exception from propagating (unless you rethrow the exception). Catching an exception gives you a chance to handle it:

  •   try {
        breedMoreLlamas();
      } on OutOfLlamasException {
        buyMoreLlamas();
      }
    
  • To handle code that can throw more than one type of exception, you can specify multiple catch clauses. The first catch clause that matches the thrown object's type handles the exception. If the catch clause does not specify a type, that clause can handle any type of thrown object:

  •   try {
        breedMoreLlamas();
      } on OutOfLlamasException {
        // A specific exception
        buyMoreLlamas();
      } on Exception catch (e) {
        // Anything else that is an exception
        print('Unknown exception: $e');
      } catch (e) {
        // No specified type, handles all
        print('Something really unknown: $e');
      }
    
  • As the preceding code shows, you can use either on or catch or both. Use on when you need to specify the exception type. Use catch when your exception handler needs the exception object.

  • You can specify one or two parameters to catch(). The first is the exception that was thrown, and the second is the stack trace (a StackTrace object).

  •   try {
        // ···
      } on Exception catch (e) {
        print('Exception details:\n $e');
      } catch (e, s) {
        print('Exception details:\n $e');
        print('Stack trace:\n $s');
      }
    
0
Subscribe to my newsletter

Read articles from Jeet Bhalu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jeet Bhalu
Jeet Bhalu

i am Jeet Bhalu i am flutter App developer