Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart Exceptions


Share

Dart Exceptions

An exception is a problem that happens while a program is running.

For example, the user types "abc" where the program expects a number.

When an exception happens and nothing handles it, the program stops and prints an error message:

Example

void main() {
  print('Start');
  var age = int.parse('abc');
  print(age);
  print('End');
}
Try it Yourself »

Result:

Start
Unhandled exception:
FormatException: Invalid radix-10 number (at character 1)
abc
^

The program printed "Start", but it never reached "End".

The error message tells you the type of the exception (FormatException) and the reason.

On your own computer, Dart also prints a stack trace, which shows where the problem happened.


try and catch

To handle an exception, put the code that can fail in a try block.

If an exception happens, Dart jumps to the catch block, and the program continues after it:

Example

void main() {
  print('Start');
  try {
    var age = int.parse('abc');
    print(age);
  } catch (e) {
    print('That is not a number');
    print(e);
  }
  print('End');
}
Try it Yourself »

Result:

Start
That is not a number
FormatException: Invalid radix-10 number (at character 1)
abc
^

End

The variable e holds the exception object, so you can print it or read its message.

The rest of the try block is skipped, so print(age) never runs.



Catch a Specific Type with on

A plain catch catches every kind of exception.

Often, you only want to handle one kind.

Use on followed by a type to catch only exceptions of that type:

Example

void main() {
  try {
    var price = double.parse('ten');
    print(price);
  } on FormatException {
    print('Please enter a valid price');
  }
}
Try it Yourself »

Result:

Please enter a valid price

You can have several on blocks, one for each type.

Add catch (e) after the type when you also need the exception object:

Example

int divide(int a, int b) {
  if (b == 0) {
    throw ArgumentError('b cannot be zero');
  }
  return a ~/ b;
}

void main() {
  for (var input in ['20', 'twenty', '0']) {
    try {
      var number = int.parse(input);
      print(divide(100, number));
    } on FormatException catch (e) {
      print('Not a number: ${e.source}');
    } on ArgumentError catch (e) {
      print('Bad argument: ${e.message}');
    }
  }
}
Try it Yourself »

Result:

5
Not a number: twenty
Bad argument: b cannot be zero

Dart checks the on blocks from top to bottom, and uses the first one that matches.


finally

The finally block always runs at the end, whether there was an exception or not.

It is used for cleanup work, like closing a file or a connection:

Example

void readScore(String text) {
  try {
    var score = int.parse(text);
    print('Score: $score');
  } on FormatException {
    print('Invalid score: $text');
  } finally {
    print('Done reading');
  }
}

void main() {
  readScore('85');
  readScore('high');
}
Try it Yourself »

Result:

Score: 85
Done reading
Invalid score: high
Done reading

throw and rethrow

You can throw an exception yourself with the throw keyword.

This is useful when a function gets a value it cannot work with:

Example

void setAge(int age) {
  if (age < 0) {
    throw Exception('Age cannot be negative');
  }
  print('Age set to $age');
}

void main() {
  try {
    setAge(25);
    setAge(-5);
  } catch (e) {
    print(e);
  }
}
Try it Yourself »

Result:

Age set to 25
Exception: Age cannot be negative

Sometimes you want to do something with an exception, like writing it to a log, and then let it continue up to the code that called you.

Use rethrow inside a catch block to throw the same exception again:

Example

int parseQuantity(String text) {
  try {
    return int.parse(text);
  } on FormatException {
    print('Log: could not read "$text"');
    rethrow;
  }
}

void main() {
  try {
    parseQuantity('five');
  } on FormatException catch (e) {
    print('main() caught: ${e.message}');
  }
}
Try it Yourself »

Result:

Log: could not read "five"
main() caught: Invalid radix-10 number

Exception vs Error

Dart has two main kinds of problems:

  • An Exception is a problem that you expect can happen, like bad user input or a missing file. Your program should catch and handle it.
  • An Error is a bug in the program, like using a list index that does not exist. You should fix the code, not catch the error.

For example, FormatException is an Exception, and RangeError is an Error:

Example

void main() {
  var fruits = ['Apple', 'Banana'];
  try {
    print(fruits[5]);
  } catch (e) {
    print(e);
    print(e is Error);
    print(e is Exception);
  }
}
Try it Yourself »

Result:

RangeError (length): Invalid value: Not in inclusive range 0..1: 5
true
false

The right fix here is to check the length of the list before you read from it.

The null safety and type checks in Dart also help you find many errors before the program runs.


The Stack Trace

A stack trace is a list of the function calls that led to the exception.

It shows you where the problem started, which is very helpful when you look for a bug.

Add a second variable to catch to get the stack trace:

Example

int parseAge(String text) {
  return int.parse(text);
}

void main() {
  try {
    parseAge('old');
  } catch (e, stackTrace) {
    print('Error: $e');
    print('Stack trace:');
    print(stackTrace);
  }
}
Try it Yourself »

Result:

Error: FormatException: Invalid radix-10 number (at character 1)
old
^

Stack trace:
#0      int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
#1      int._parseRadix (dart:core-patch/integers_patch.dart:179:14)
#2      int._parse (dart:core-patch/integers_patch.dart:121:12)
#3      int.parse (dart:core-patch/integers_patch.dart:81:12)
#4      parseAge (main.dart:2:14)
#5      main (main.dart:7:5)
#6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#7      _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

Read the stack trace from the top: the first lines are inside Dart's own code, and then you find your own functions, parseAge and main, with their line numbers.

Tip: In the next chapter, you will learn how to create your own custom exceptions.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.