Open In App

Dart – Types of Exceptions

Improve
Improve
Like Article
Like
Save
Share
Report

Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occurred because of a programmer’s mistake or by wrong user input. To handle such events at runtime is called Exception Handling. For example:- when we try to access the elements from the empty list. Dart Exceptions are the run-time error. It is raised when the program gets execution.  

Built-in Exceptions in Dart:

The below table has a listing of principal dart exceptions.

Sr.  Exceptions Description
1 DefferedLoadException It is thrown when a deferred library fails to load.
2 FormatException  It is the exception that is thrown when a string or some other data does not have an expected format
3 IntegerDivisionByZeroException It is thrown when the number is divided by zero.
4 IOEException It is the base class of input-output-related exceptions.
5 IsolateSpawnException It is thrown when an isolated cannot be created.
6 Timeout It is thrown when a scheduled timeout happens while waiting for an async result.

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
}
  1. Try: In the try block, we write the logical code that can produce the exception
  2. Catch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used.
  3. On: On the block is used when it is 100% sure what kind of exception will be thrown.
  4. Finally: The final part is always executed, but it is not mandatory.

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

Dart




// importing dart:io file
import 'dart:io';
 
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.

Explanation:

In the above code, we declared two-variable geek and geek2 in the main () function. We wrote the suspect code in try block divided the x by the 0 that might be thrown an exception. The try block found the error the control transferred to the block that has the code to handle the error. By using this, the program did not stop its execution.

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

Dart




void main() {
    String geek = "GeeksForGeeks";
        try{
            var geek2 = geek ~/ 0;
            print(geek2);
        }
   
        // It returns the built-in exception
        // related to the occurring exception 
        catch(e){
            print(e);
        }
}


Output:

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

Example 3: Using an on…catch block in the dart.

Dart




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


Output:

FormatException

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 the finally block if you include it then it should be after try and catch block are over.

Syntax:
try {   
  .....  
}    
on Exception1 { 
  ....  
}    
catch Exception2 {  
  ....
}    
finally {   
   // code that should always execute; whether exception or not.  
}  

Example:

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.");
    }
      finally {
        print("Code is at end, Geek");
      }    
   
}


Output:

Error!! 
Can't act as input is not an integer.
Code is at end, Geek

Throwing an exception

The throw keyword is used to explicitly raise an exception. Dart provides many built-in exception classes which you can throw manually.

Syntax: throw new Exception_name()  

Example:

Dart




void main() {  
   try {  
      geek(-5);  
   }  
   catch(e) {  
      print('The marks cannot be negative');  
   }  
}   
void geek(int div2) {  
   if(div2<0) {  
      throw new FormatException();  // Raising explanation externally 
   }  


Output:

The marks cannot be negative

In the above program, we have wrapped geek(-5) statement in try block because it can throw an exception.

Custom Exceptions

Every exception class inherits from the Exception class. Dart enables creating custom exceptions by extending the existing ones.

Syntax: class Custom_exception_Name implements Exception { }   

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 

In the above example, we created a custom exception, Age. The code raised the exception if the entered amount is not within the excepted range, and we enclosed the function invocation in the try…catch block. 



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