×

Dart Exception Handling

Exception Class –

An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught and should contain useful message to be displayed so that the compilation can continue.

Constructors

  1. Exception –

Implementation –

factory Exception([var message]) = > _Exception(message);

Properties

  1. HashCode=

Returns the hash code for a numerical value, and it returns the same value for int and doubles when the value provided is the same.

Implementation = int get hashchode;

  1. Runtime Type=

Represents the type of runtime an object has.

Implementation = Type get runtimeType;

Methods

  1. noSuchMethod –

This method is invoked when a non-existent method or property is accessed.

Implementation =

@pragma("vm:entry-point")

external dynamic noSuchMethod(Invocation invocation);

  1. toString( )=

Converts a given number into an equivalent shortest string and returns the same.

Implementation = external String toString( );

Dart Exceptions

These are the run-time errors that occur when the program gets executed. This error doesn’t show up at the time of compilation error, and the program is terminated abnormally.

Example – If we try to access the file that actually does not exist.

The aim of having exception handling in any programming language is to handle the run-time error and preventing the program from terminating abruptly.

Following is the list of types of built-in exceptions :

Sr.

Exceptions

Description

1.

DefferedLoadException

It is thrown when a deferred library fails to load.

2.

FromatException

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

3.

IntegerDivisionByZeroException

It is thrown when number is divided by zero.

4.

IOException

It is the base class of input-output related exception.

5.

IsolateSpawnException

It is thrown when an isolate cannot be created.

6.

Timeout

It is thrown when a schedule timeout happens while waiting for an async result.


The try/on/catch Blocks

The try block is used to hold the block of code that might throw an exception. We use on block when the exception type is required to be specified. While, the catch block is used when the handler needs the exception object.

If the try block falls through any error, it throws that error to the catch block which then handles the error using the code. The try block must be followed by either exactly one  on/ catch or one finally block.

Consider the syntax of exception handling : -

try {

// code that might throw an exception

}

on Exception1 {

// specify the exception

}

Catch Exception2 {

// code for handling exception

}

Remember the following points with respect to exception handling :-

  • We can handle the multiple exceptions using more than one on / catch block.
  • There is mutually inclusion between the on block and the catch block that means we can associate both the on block and catch block with the try block.

In the following example, the variable x is divided by the y variable respectively. The code is thrown when it tries to divide by the zero. The on block consists of the code to handle the exception. Let's understand the following code.

Example - Using the on block

void main( ) {  

   int x = 15 ; 

   int y = 0 ; 

   int res ;   

   

   try {

      res = x ~/ y ; 

   } 

   on IntegerDivisionByZeroException { 

      print( ' Cannot divide by zero ' ) ; 

   } 

}

Output

Cannot divide by zero

Explanation :

In the above code, three variables x, y and res have been declared in main( ) function. As we know that the division of a number by 0 is undefined, we write the suspected code in the try block. The try block found the error and transfer the control to the on block that has the code to handle the error. By doing so, the program didn’t terminate abruptly.

Let's understand the following example using the catch block.

Example - Using the catch Block

void main( )

{ 

   int x = 5 ; 

   int y = 0 ; 

   int res ;   

   

   try {   

      res = x ~/ y ; 

   }   




   catch( E ) { 

      print( E ) ; 

   } 

}

Output

IntegerDivisionByZeroException

Consider the same code with the on…catch block

void main( ) {  

   int x = 5 ; 

   int y = 0 ; 

   int res ;   

   

   try { 

      res = x ~/ y ; 

   }   

   on IntegerDivisionByZeroException catch( E ) { 

      print( E ) ; 

   } 

}

Output

IntegerDivisionByZeroException

The Finally Block

The finally block always executes irrespective of any exception present or not in the program. It executes unconditionally after the try/on/catch.

The syntax of finally block is given below:

try {  

   // code that may be throw an exception 

}   

on Exception1 { 

   // exception handling code or specifying the exception

}   

catch Exception2 { 

   //  code for exception handling 

}   

finally { 

   // code that should always execute; whether exception or not.

}

Example –

Consider the following code in Dart that explains the finally block

finally

{ void main( ) { 

   int x = 5 ; 

   int y = 0 ; 

   int res ;   

   

   try { 

      res = x ~/ y ; 

   } 

   on IntegerDivisionByZeroException { 

      print( ' Cannot divide by zero ' ) ; 

   } 




      print( ' Finally block always executed ' ) ; 

   } 

}

Output

Cannot divide by zero

Finally block executed

Explanation

Even though the division is undefined here and therefore the program must ideally throw an exception but since we used ‘finally’ here the program still executed.

Throwing an Exception

An exception can be raised explicitly or forcefully using the ‘throw’ keyword. The explicitly raised exception should be handled to avoid the program from existing abruptly.

Syntax:

throw new Exception_name( )

Consider the following code in Dart that explains the above point,

Example -

main( ) {  

   try { 

      check_marks( -10 ) ; 

   } 

   catch( e ) { 

      print( ' The marks cannot be negative ! ' ) ; 

   } 

}   

void check_marks( int marks ) { 

   if( marks < 0 ) { 

      throw new FormatException( ) ;  // Raising explanation externally

   } 

}

Output

The marks cannot be negative !

Custom Exceptions

As we discussed above, each of the exception in dart is the subtype of the built-in class Exception. Dart provides the flexibility to create custom exception by extending the existing exception class. The syntax is given below.

Syntax: Defining the Exception

class Custom_exception_Name implements Exception { 

  // can contain constructors, variables and methods 

}


Related Topics

Dart Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 minutes read.

main function in Dart

The main( ) function is a predefined method in Dart that is also known as the entry-point of the program. The compiler begins the execution only when it comes across...

3 minutes read.

Dart Concurrency

Dart concurrency allows us to run multiple or multiple components of a system at once. It issues several commands at once. Dart provides Isolates as a tool for performing compliance...

2 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional. By default,...

4 minutes read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

Dart Inheritance

Inheritance is a promising concept of any programming language. It is a property by which a class inherits the property of another class. Moreover, the class deriving the properties of...

5 minutes read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Dart Equality and Relational Operators

Dart provides the functionality of checking the relationship between the values or values within the variables. These operators return the resultant value as Boolean, i.e., either ‘true’ or ‘false’. Some important points...

3 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Type System in Dart

Dart language is a type safety enabled language that uses static and dynamic type checking to match the value of the variable with its data type at the compile-time. This...

4 minutes read.

Dart URIs

The Uri class supports encoding and decoding of strings with the help of functions to be used in URIs ( which may also be known as URLs ). These functions...

6 minutes read.