VOOZH about

URL: https://www.geeksforgeeks.org/dart/exception-handling-in-dart/

⇱ Exception Handling in Dart - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Exception Handling in Dart

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 :

Output:

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


Using a try-catch block

👁 try-catch


Example :

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:

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:


Output:

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

Explore