Dart try catch

Summary: in this tutorial, you’ll learn how to use the Dart try-catch statement to handle exceptions in programs.

Introduction to the Dart try-catch statement

Exceptions are errors that may occur in the program. If you don’t catch the exceptions and handle them properly, the program will crash.

For example, the following program defines a string variable message and attempts to access the character at index 5:

void main() {
  String message = "Hello";
  print("The character at the position 5 is ${message[5]}.");
  print('Bye!');
}Code language: Dart (dart)

The program crashed and issued the following error:

Unhandled exception:
RangeError (index): Invalid value: Not in inclusive range 0..4: 5Code language: Dart (dart)

The error message shows that the RangeError exception was unhandled.

To prevent the program from crashing, you need to handle the exception. To do that, you use the try catch statement:

try {
   // code that may cause an exception
} catch(e) {
   // code that handles the exception
}Code language: Dart (dart)

In the try-catch statement, you place the code that may cause an exception in the try block. If an exception occurs, the program jumps to the catch block immediately and skips the remaining code in the try block.

In the catch block, you place the code that handles the exception. In practice, you may want to recover from the exception as much as possible such as by showing a user-friendly message.

Also, you can access the exception object (e) in the catch block. All exception classes are the subclasses of the Exception class.

For example, the following program uses the try-catch statement to catch the RangeError exception:

void main() {
  String message = "Hello";

  try {
    print("The character at the position 5 is ${message[5]}.");
  } catch (e) {
    print(e);
  }

  print('Bye!');
}Code language: Dart (dart)

Output:

RangeError (index): Invalid value: Not in inclusive range 0..4: 5
Bye!Code language: Dart (dart)

In this example, the message[5] causes the RangeError exception. However, the program doesn’t crash. and runs to the end.

Stack trace

A stack trace is a list of function or method calls that lead to the exception. The catch() accepts a second parameter that represents a stack trace. For example:

void fn() {
  String message = "Hello";
  try {
    print("The character at the position 5 is ${message[5]}.");
  } catch (e, s) {
    print(e);
    print(s);
  }
}

void main() {
  fn();
  print('Bye!');
}
Code language: PHP (php)

Output:

RangeError (index): Invalid value: Not in inclusive range 0..4: 5
#0      _StringBase.[] (dart:core-patch/string_patch.dart:260:41)
#1      fn (file:///D:/dart/main.dart:4:56)
#2      main (file:///D:/dart/main.dart:12:3)
#3      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

Bye!Code language: PHP (php)

In practice, you only specify the second parameter of the catch clause if your code requires access to the stack trace.

The on clauses

If you know the exact exception that may occur, you can use the try-catch statement with the on clauses like this:

try {
  // code that may cause the exception
} on Exception1 catch(e) {
  // handle Exception1
} on Exception2 catch(e) {
  // handle Exception2
} catch (e) {
  // handle other exceptions
}Code language: Dart (dart)

In this syntax, the try-catch statement may have multiple on clauses, each handling a specific exception.

If the exception is not either Exception1 or Exception2, the final catch clause will execute to handle the unspecified exception.

For example, the following program uses the try-catch statement with the on clause to catch the RangeError exception:

void main() {
  String message = "Hello";

  try {
    print("The character at the position 5 is ${message[5]}.");
  } on RangeError {
    print('The valid range for the index is [0..${message.length - 1}].');
  } catch (e) {
    print(e);
  }

  print('Bye!');
}Code language: Dart (dart)

Output:

The valid range for the index is [0..4].
Bye!Code language: Dart (dart)

Also, you can add the catch to the on the statement to access the exception object. For example:

void main() {
  String message = "Hello";
  try {
    print("The character at the position 5 is ${message[5]}.");
  } on RangeError catch (e) {
    print(e);
  } catch (e) {
    print(e);
  }
  print('Bye!');
}Code language: PHP (php)

Output:

RangeError (index): Invalid value: Not in inclusive range 0..4: 5
Bye!Code language: JavaScript (javascript)

Summary

  • Use the try-catch statement to handle the exception.
  • Use on clauses in the try-catch statement to handle the specific exceptions.
Was this tutorial helpful ?