Catch

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

  1. try {
  2. breedMoreLlamas();
  3. } on OutOfLlamasException {
  4. buyMoreLlamas();
  5. }

To handle code that can throw more than one type of exception, you canspecify multiple catch clauses. The first catch clause that matches thethrown object’s type handles the exception. If the catch clause does notspecify a type, that clause can handle any type of thrown object:

  1. try {
  2. breedMoreLlamas();
  3. } on OutOfLlamasException {
  4. // A specific exception
  5. buyMoreLlamas();
  6. } on Exception catch (e) {
  7. // Anything else that is an exception
  8. print('Unknown exception: $e');
  9. } catch (e) {
  10. // No specified type, handles all
  11. print('Something really unknown: $e');
  12. }

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

  1. try {
  2. // ···
  3. } on Exception catch (e) {
  4. print('Exception details:\n $e');
  5. } catch (e, s) {
  6. print('Exception details:\n $e');
  7. print('Stack trace:\n $s');
  8. }

To partially handle an exception,while allowing it to propagate,use the rethrow keyword.

  1. void misbehave() {
  2. try {
  3. dynamic foo = true;
  4. print(foo++); // Runtime error
  5. } catch (e) {
  6. print('misbehave() partially handled ${e.runtimeType}.');
  7. rethrow; // Allow callers to see the exception.
  8. }
  9. }
  10.  
  11. void main() {
  12. try {
  13. misbehave();
  14. } catch (e) {
  15. print('main() finished handling ${e.runtimeType}.');
  16. }
  17. }