Open In App

Exception Handling in Dart

Improve
Improve
Like Article
Like
Save
Share
Report

An exception is an error that takes place 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 to prevent the application from termination. 

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
}

Example 1: Using a try-on block in the dart. 

Dart




void main() {
  String geek = "GeeksForGeeks";
  try{
    var geek2 = geek ~/ 0;
    print(geek2);
  }
  on FormatException{
    print("Error!! \nCan't act as input is not an integer.");
  }
}


 

Output:  

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

Example 2: Using a try-catch block in the dart. 

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 {
   ...
}

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. 

Example: Creating custom exceptions in the dart. 

Dart




// extending Class Age
// with Exception class
class Age implements Exception {
  String error() => '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.error());
  }
}
 
// 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 :(


Last Updated : 14 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads