Try Catch Finally

    Dart try, catch and finally blocks helps in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exception by executing alternate application logic or handle the exception gracefully to report back to the user. It helps in preventing the ugly application crashes.


  1. Try Catch
  2. Try Catch statement allows you to handle Errors or Exceptions without actually exiting the execution when an Exception or Error occurs.

    The try block contains the application code which is expected to work in normal conditions. Then if at all an exception occurs, the object is sent to the catch block. You can access the exception object and continue with the program execution. In catch block, you can write program statements.

    Example:


    void main() {

      String txt = "Dart";

      try {

        for (int i = 0; i < 10; i++) {

          print(txt[i]);

        }

      } catch (exception) {

        print("Something Wrong happened");

        print(exception);

      }

    }



    D
    a
    r
    t
    Something Wrong happened
    RangeError (index): Invalid value: Not in inclusive range 0..3: 4

  3. Try On Catch
  4. Catch block can handle any type of Exception or Error. But if you want to handle a specific type of Error or Exception in some different way, you can use on keyword.

    Each on-block can handle specified Exception or Error.


    Example:


    void main() {

      var list = [151601545];

      try {

        for (int i = 0; i < 10; i++) {

          print(list[i] ~/ list[i + 1]);

        }

      } on RangeError {

        print("Error: Out of range for list.");

      } on IntegerDivisionByZeroException {

        print("Error: Integer Division by Zero");

      } catch (exception) {

        print("Something unknown happened");

        print(exception);

      }

    }



    0
    0
    Error: Integer Division by Zero

  5. Finally
  6. An optional finally block gives us a chance to run the code which we want to execute EVERYTIME a try-catch block is completed – either with errors or without any error.

    The finally block statements are guaranteed of execution even if we fail to handle the exception successfully in catch block.

    Example:


    void main() {

      var list = [105016301545];

      try {

        for (int i = 0; i < 10; i++) {

          print(list[i] ~/ list[i + 1]);

        }

      } on RangeError {

        print("Error: Out of range for list.");

      } on IntegerDivisionByZeroException {

        print("Error: Integer Division by Zero");

      } catch (exception) {

        print("Something Wrong happened");

        print(exception);

      } finally {

        print("We reach the finally block");

      }

    }



    0
    3
    0
    2
    0
    Error: Out of range for list.
    We reach the finally block