Table of contents
1.
Introduction
2.
Types of Exceptions
3.
Exception Handling
3.1.
Using the try-catch block
3.2.
Using the Finally Block
3.3.
Using Throwing an Exception
3.4.
Using Custom Exception
4.
Frequently Asked Questions
4.1.
What is the run-time error?
4.2.
Can we write multiple catch blocks with one try block?
4.3.
Can we associate both on and catch block with one try block?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Dart Exception Handling

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will be learning about Exception handling in Dart. Before learning exception handling, let's first know about the exception. There exist two types of error when we run our code compile-time error and run-time error, exception is a problem that comes under the run-time error of our code. While having an exception, the execution of our program terminates abnormally.

To deal with these exceptions, dart provides an Exception Handling mechanism that lets the users know why their program's execution gets disrupted. The exception is a class with every exception as its subtype, and exceptions must be handled to prevent our code from terminating abnormally.

Types of Exceptions

In a programming language, exceptions are of several types. Let's discuss some of the exceptions that dart supports in its Exception class:

Exception Handling

We divide our code that may create exceptions into blocks using try/on/catch blocks to handle these exceptions. The try block contains code that could potentially throw an exception. When the exception type must be provided, the block is utilized. When the handler requires the exception object, the catch block is used. 

If the try block encounters an error, it passes control to the catch block, containing the code to manage the situation. An on/catch or a finally block always follows a try block. 

Syntax:

try {
  // code that might throw an exception
}
on Exception1 {
  // Specifying exception
}
Catch Exception2 {
  // Handling exception
}


Finally Block: In dart, the final block is used to include specific code that must be executed regardless of any errors. Although including the finally block is optional, if you do, it should come after the try and catch blocks have been completed.

Syntax:

try {   
   // code that may throw an exception   
}    
on Exception1 {   
   // Specifying exception  
}    
catch Exception2 {   
   // Handling exception  
}    
finally {   
   // This block always execute irrespective of exception.  
} 

Now let’s discuss the implementation of these blocks:

Using the try-catch block

Below is an example showing the usage of try and catch block handling. When the try block catches, the error control gets transferred to the catch block preventing the code stops abnormally.

Code:

void main() {   
   int a = 120;   
   int b = 0;   
   int result;    
     
   try {    
      result = a ~/ b;   
   }    
  //'E' return the built-in exception according to the exception occurred.
   catch(E) {   
      print(E);   
   }   
}

Output:

Unsupported operation: Result of truncating division is Infinity: 120 ~/ 0

Explanation: In the example above, we are trying to divide a number by zero, so it shows an exception for that.

Using the Finally Block

Irrespective of an exception, the finally block is always executed. After the try/on/catch, it executes unconditionally.

Code:

void main() {   
   int a = 120;   
   int b = 0;   
   int result;    
     
   try {    
      result = a ~/ b;   
   }    
  //'E' return the built-in exception according to the exception occurred.
   catch(E) {   
      print(E);   
   }
   finally{
      print("Your execution has come to an end.");
      print("You are in the finally block.");
   }
} 

Output:

Unsupported operation: Result of truncating division is Infinity: 120 ~/ 0
Your execution has come to an end.
You are in the finally block.

Explanation: In this example, we are using the case of a number divided by zero to show the working of try, catch and finally blocks.

Using Throwing an Exception

Using the throw keyword, we can raise an exception explicitly. After throwing an exception, the exception will be handled to let the user know what has gone wrong.

Syntax:

throw Exception_type()

Example: In this example, we will show the use case of throwing an exception.

Code:

void main()
{
   int age = 16;
   print("1. Candidate of age $age is entering in onlyAdult function.");
   print("Message:");
   try { 
      //Passing the parameters.
      onlyAdult(age);   
   }   
   catch(e) { 
      //Catching and handling the thrown exception.
      print('Children and teens are not allowed.');   
   }
   //New Entry.
   age = 26;
   print("2. Candidate of age $age is entering in onlyAdult function.");
   print("Message:");
   try { 
      //Passing the parameters.
      onlyAdult(age);   
   }   
   catch(e) { 
      //Catching and handling the thrown exception.
      print('Children and teens are not allowed.');   
   }
}    
void onlyAdult(int age)
{   
   if(age<18) { 
      //Throwing the exception.
      //Raising the exception externally.
      throw FormatException(); 
   }
   print("You are an Adult of age: $age.");
}  

Output:

1. Candidate of age 16 is entering in onlyAdult function.
Message:
Children and teens are not allowed.
2. Candidate of age 26 is entering in onlyAdult function.
Message:
You are an Adult of age: 26.

Explanation: In this example, we make a function onlyAdult() which takes age as an argument. If the age passed is less than 18, then the function will throw an exception.

Using Custom Exception

Each exception in dart is a subclass of the built-in class Exception, as we covered earlier. Dart allows you to extend the existing exception class to build your own custom exceptions.

Syntax:

class Custom_Exception_Type implements Exception {   
   // Define the class using constructor, fields and methods.   
}

Example: In this example, we will show the use case of a custom-defined exception.

Code:

//Creating custom class.
class WeaponsException implements Exception {   
   String msg(){
     return 'Weapons are not allowed.';
   }   
}
//Creating custom class.
class PetException implements Exception {   
   String msg(){
     return 'Pets are not allowed.';
   }   
}

void main()
{   
   try {   
      onThePlane(false,true);   
   }   
   on WeaponsException{
      WeaponsException E = WeaponsException();
      print(E.msg());   
   }
   on PetException{
      PetException E = PetException();
      print(E.msg());   
   }
   finally {   
      print('Leave the restricted things and get on the plane.');   
   }   
}

void onThePlane(bool weapon, bool pet)
{   
   if (weapon) {
     //Throwing the custom exception.
      throw WeaponsException();   
   }
   if(pet) {
     //Throwing the custom exception.
     throw PetException();
   }
   print("Get on the Plane");
} 

Output:

Pets are not allowed.
Leave the restricted things and get on the plane.

Explanation: In this example, we made two classes for the exception and which implement the Exception interface. We use these class names to throw exceptions.

Frequently Asked Questions

What is the run-time error?

Only during the execution of the program do run-time faults occur. Run-time errors indicate program faults or issues that the developers were aware of but were unable to resolve.

 

Can we write multiple catch blocks with one try block?

Yes, we can write multiple blocks with one try block. The catch block with the proper exception will work and throw the exception accordingly.

 

Can we associate both on and catch block with one try block?

Yes, we can associate both on and catch blocks with one try block because the on and catch blocks are mutually inclusive. We can associate both the on and catch blocks with the try block.

Conclusion

In this article, we've extensively discussed Exception Handling in dart and its implementation. We have discussed using different combinations of try/ on/ catch/ finally/ throw and custom exceptions.

We hope that this blog has helped you enhance your knowledge regarding the Exception Handling of Dart. We can use the concepts of Java in building an android app to learn in-depth about android development. Check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass