Exception Handling in Dart (original) (raw)

Last Updated : 18 Apr, 2025

An exception is an error that occurs inside the program. When an exception occurs inside a program, the normal flow of the program is disrupted, and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care of to prevent the application from terminating.

**Built-in Exceptions in Dart:

Built-in Exceptions in Dart: 

Every built-in exception in Dart comes under a pre-defined class named **Exception. To prevent the program from exception, we make use of **try/on/catch blocks in Dart.

try {
// program that might throw an exception
}
on Exception1 {
// code for handling exception 1
}
catch Exception2 {
// code for handling exception 2
}

Using a try-on block

**Example :

Dart `

void main() { String geek = "GeeksForGeeks"; try { int result = int.parse(geek); } on FormatException { print('Error!! \nCan't act as input is not an integer.'); } }

`

**Output:

Error!!
Can't act as input is not an integer.

Using a try-catch block

try-catch

**Example :

Dart `

void main() { String geek = "GeeksForGeeks"; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); } }

`

**Output:

Class 'String' has no instance method '/'.
NoSuchMethodError: method not found: '
/'
Receiver: "GeeksForGeeks"
Arguments: [0]

**Final block: The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include finally block if you include it then it should be after try and catch block are over.

finally {
...
}

Using a try-catch-finally block

try-catch-finally_block

**Example:

Dart `

void main() { int geek = 10; try{ var geek2 = geek ~/ 0; print(geek2); } catch(e){ print(e); } finally { print("Code is at end, Geek"); } }

`

**Output:

Unsupported operation: Result of truncating division is Infinity: 10 ~/ 0
Code is at end, Geek

Unlike other languages, in Dart to one can create a custom exception. To do, so we make use of **throw new keyword in the dart.

Creating custom exceptions

creating_custom_exception

**Example:

Dart `

// extending Class Age // with Exception class class Age implements Exception { String toString() => 'Geek, your age is less than 18 :('; }

void main() { int geek_age1 = 20; int geek_age2 = 10;

try {
    // Checking Age and
    // calling if the
    // exception occur
    check(geek_age1);
    check(geek_age2);
} catch (e) {
    // Printing error
    print(e);
}

}

// Checking Age void check(int age) { if (age < 18) { throw new Age(); } else { print("You are eligible to visit GeeksForGeeks :)"); } }

`

**Output:

You are eligible to visit GeeksForGeeks :)
Geek, your age is less than 18 :(