×

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

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 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 Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 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 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...

4 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute 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 Sets

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart Packages

Every programming language has some in-built functions stored inside the header files that makes the task much easier for the programmer. The Dart Packages refer to the compilation of a...

4 minutes read.

Dart Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 minutes read.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes 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.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

2 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.