Skip to main content

Dart Exception Handling With Examples

 

Dart Exception Handling With Examples


Exception Handling is one of the main core aspects of any programming language and it is one of the best practice to follow. Like any other rich programming language, Dart offers Exception Handling. We will understand this concept and I will show you Dart Exception Handling With Examples.


What is Exception Handling

Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occured because of programmer’s mistake or by wrong user input.

To handle such events at runtime is called Exception Handling.


Types of Exceptions in Dart

There are quite a few built-in exceptions handling methods in Dart. Let’s focus on some of the main exceptions and their description

NoException and Description
1
Integer Division By Zero Exception

Thrown when a number is divided by zero.

2
IO Exception

Base class for all Input-Output related exceptions.

3
Deferred Load Exception

Thrown when a deferred library fails to load.

4
Format Exception

An exception is thrown when a string or some other data does not have an expected format and cannot be parsed or processed.

5
Isolate  Spawn Exception

Thrown when an isolate cannot be created.

6
Time out

Thrown when a scheduled timeout happens while waiting for an async result.


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.



In Dart Exceptions can be handle via

  • Try: In the try block, we write the logical code that can produce the exception
  • 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.
  • On: On block is used when it is 100% sure what kind of exception will be thrown.
  • Finally: The finally part is always executed but it is not mandatory.
As for now, we have some understanding of exceptions and how can we handle them. Let do this via code.


Dart Exception Handling With Examples

In this tutorial, we will focus only on IntegerDivisionByZeroException. First of all, write an exception-free code.

void main() {
try {
int firstInput = 20;
int secondInput = 4;
int result = firstInput ~/ secondInput;
print('The result of $firstInput divided by $secondInput is $result');
} catch (e) {
print('Exception occurs: $e');
}
}

The output is

The result of 20 divided by 4 is 5

Now suppose the secondInput value is 0. In this case, there will be an exception and it is pretty much sure its IntegerDivisionByZeroException. In this case, the “on” block can be used along with “try” block.

void main() {
try {
int firstInput = 20;
int secondInput = 0;
int result = firstInput ~/ secondInput;
print('The result of $firstInput divided by $secondInput is $result');
} on IntegerDivisionByZeroException {
print('The division by 0 is causing Exception ');
}
}

The response of console

The division by 0 is causing Exception

Imagine there is a huge logical coding block with integer values and other data types. It is not sure what can be the cause of the Exception. In that case, the “catch” block is a good option. Catch block when not sure what kind of exception can be thrown.

And the expected result

Exception occurs: IntegerDivisionByZeroException

Till now everything looks fine. What about the “finally” block. As said before it will get executed no matter what. Let’s explore

void main() {
try {
int firstInput = 20;
int secondInput = 0;
int result = firstInput ~/ secondInput;
print('The result of $firstInput divided by $secondInput is $result');
} catch (e) {
print('Exception occurs: $e');
} finally {
print('There is an Exception occurred but I am still getting called');
}
}

The expected messages on the console.

Exception occurs: IntegerDivisionByZeroException
There is an Exception occurred but I am still getting called

Stack Trace Exception


Stack Trace Exception: Stack trace helps you to trace the events that occurred before the exception was thrown

A Stack Trace is a list of the method calls that the application was in the middle of when an Exception was thrown. The most useful information is normally shown at the top of StackTraces, so you should always look at them from the ‘top down’. Sometimes this takes a lot of scrolling up!

Consider the try catch example code but this time with Stack Trace Exception.

void main() {
try {
int firstInput = 20;
int secondInput = 0;
int result = firstInput ~/ secondInput;
print('The result of $firstInput divided by $secondInput is $result');
} catch (e, s) {
print('Exception occurs: $e');
print('STACK TRACE\n: $s');
}
}

Pretty simple just pass a parameter along with exception in catch block. Here is the output.

Exception occurs: IntegerDivisionByZeroException
STACK TRACE
:#0 int.~/ (dart:core/runtime/libintegers.dart:18:7)
#1 main (file:///Users/Waheed/IdeaProjects/FlutterRDart/bin/main.dart:5:29)
#2 _startIsolate.<anonymous closure=""> (dart:isolate/runtime/libisolate_patch.dart:289:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
</anonymous>



Comments

All Post

When to Use Waterfall vs. Agile

  We compare the benefits and drawbacks of using two well-known software development methodologies, Waterfall and Agile, and lay out when it might be more suitable to use one over the other – or combine practices of both – for your product initiative. When developing a new software product, your team will need to navigate which development methodology is right for your initiative. In the world of managing  software development  projects, the topic of Agile vs Waterfall is widely debated. Many thought leaders and Agile enthusiasts in the industry have argued Waterfall is dead, however, traditional organizational environments and processes have led to it still being widely used today. A 2017 report from the Project Management Institute shows that  51% of the organizations surveyed use Waterfall either often or always . The reality is, each software development project poses its own unique challenges and requirements. It’s not a matter of deciding which development meth...

Flutter form validation: Full guide for you to make Flutter form

  Flutter form validation Getting started with form validation in Flutter The Flutter SDK provides us with an out-of-the-box widget and functionalities to make our lives easier when using form validation. In this article, we’ll cover two approaches to form validation: the form widget and the Provider package. You can find more information on these two approaches in the official Flutter docs. Creating a form in Flutter First, we are going to create a simple login page that has the following fields: Email Name Phone number Password For the validation, we want the users of our app to fill in the correct details in each of these fields. The logic will be defined as such: First, for the name field, we want the user to enter a valid first name and last name, which can be accompanied by initials. For the email field, we want a valid email that contains some characters before the “@” sign, as well as the email domain at the end of the email. For phone number validation, the user is expecte...

How to change the language on Android at runtime and don’t go mad

  How to change the language on Android at runtime and don’t go mad TL;DR There is a library called Lingver that implements the presented approach with just a few lined of code.  Check it out! Introduction The topic is old as the hills, but still is being actively discussed among developers due to frequent API and behavior changes. The goal of this post is to gather all tips and address all pitfalls while implementing this functionality. Disclaimer Changing the language on Android at runtime was never officially encouraged or documented. The resource framework automatically selects the resources that best match the device. Such behavior is enough for common applications, so just make sure you have strict reasons to change it before proceeding further. There are a ton of articles and answers on Stack Overflow but they usually lack enough of explanation. As a result, when this functionality gets broken, developers can’t easily fix it due to the messy API and lots of deprecated t...

7 Key Android Concepts

  Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Moreover, the use of these Android concepts is vital in developing an application quickly – custom Android designs can take up to 10 times longer! Android UI Controls Android provides a number of standard UI controls that  enable a rich user experience . Designers and developers should thoroughly understand all of these controls for the following reasons: They are faster to implement. It can take up to ten times longer to develop a custom control than to implement a user interface with standard Android controls. They ensure good performance. Custom controls rarely function as expected in their first implementation. By implementing standard controls, you can eliminate the need to test,...

Clean Code and the Art of Exception Handling

  Clean Code and the Art of Exception Handling Exceptions are as old as programming itself. An unhandled exception may cause unexpected behavior, and results can be spectacular. Over time, these errors have contributed to the impression that exceptions are bad. But exceptions are a fundamental element of modern programming. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable. Exceptions are as old as programming itself. Back in the days when programming was done in hardware, or via low-level programming languages, exceptions were used to alter the flow of the program, and to avoid hardware failures. Today, Wikipedia  defines exceptions as: anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution specialized programming language constructs or computer h...

How to them the background of the Android options menu items

  “What we’ve got here is… failure to theme. Some views you just can’t reach. So you get what we had here last project, which is the way Android wants it… well, it gets it. I don’t like it any more than you men.” – Captain, Road Prison 36 Some of you might recognize the previous paragraph as the introduction of Guns ‘N Roses’ Civil War or from the movie Cold Hand Luke starring Paul Newman. This is the feeling I get when I try to create a custom theme for an application on Android. The Android SDK does permit some level of theming, which is not really well documented to start with. Other things are hard-coded, “so you get what we had here last project”. Now, one of the things your application will most likely use is the Options menu, which is the menu you see when you press the hard menu key. It is kind of… orange. In our last project, we had to completely remove the orange in favor of our customer’s color scheme, which is on the blue side. I couldn’t find a way to change the menu i...

Android Jetpack Compose

  Jetpack Compose Tutorial for Android: Getting Started Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs. At Google I/O 2019, Google first announced  Jetpack Compose . Jetpack Compose is Google’s response to the declarative UI framework trend, which the Android team is developing to fundamentally change the way developers create UI, making it easier and faster to write, and more performant to run. It is a part of the Jetpack suite of libraries and as such should provide compatibility throughout platform versions, removing the need to avoid certain features, because you’re targeting lower-end devices or older versions of Android. Although it’s still in an alpha , Compose is already making big waves in the Android community. If you want to stay up-to-date on the latest and greatest technology, read on! In this tutor...

Loops in Dart 💪💪💪😎😎😎

       Loops in Dart   💪💪💪😎😎😎 Dart Loops In Programming, loops are used to repeat a block of code until certain conditions are not completed. For, e.g., if you want to print your name 100 times, then rather than typing print(“your name”); 100 times, you can use a loop. There are different types of loop in Dart. They are: For Loop For Each Loop While Loop Do While Loop Info Note : The primary purpose of all loops is to repeat a block of code. Print Your Name 10 Times Without Using Loop Let’s first print the name 10 times without using a loop. void main() { print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); print( "John Doe" ); } Show Output ...

MVVM architecture, ViewModel and LiveData (Part 1)

  MVVM architecture, ViewModel and LiveData (Part 1) During Google I/O, Google introduced  architecture components  which includes  LiveData  and  ViewModel  which facilitates developing Android app using MVVM pattern. This article discusses how can these components serve an android app that follows MVVM. Quick Definition of MVVM If you are familiar with MVVM, you can skip this section completely. MVVM is one of the architectural patterns which enhances separation of concerns, it allows separating the user interface logic from the business (or the back-end) logic. Its target (with other MVC patterns goal) is to achieve the following principle  “Keeping UI code simple and free of app logic in order to make it easier to manage” . MVVM has mainly the following layers: Model Model represents the data and business logic of the app. One of the recommended implementation strategies of this layer, is to expose its data through observables to be decoupled ...