Dart Exceptions

An exception (or exceptional event) is a problem that arises during the execution of a program.

Sr.NoExceptions & Description
1DeferredLoadException Thrown when a deferred library fails to load.
2FormatException Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed.
3IntegerDivisionByZeroException Thrown when a number is divided by zero.
4IOException Base class for all Input-Output related exceptions.
5IsolateSpawnException Thrown when an isolate cannot be created.
6Timeout Thrown when a scheduled timeout happens while waiting for an async result.

Every exception in Dart is a subtype of the pre-defined class Exception.

The try / on / catch Blocks :

The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified.

The catch block is used when the handler needs the exception object.

The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch.

try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // code for handling exception 
}  
catch Exception2 { 
   // code for handling exception 
} 

Example: Using the ON Block:

The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception.

main() { 
   int x = 12; 
   int y = 0; 
   int res;  
   
   try {
      res = x ~/ y; 
   } 
   on IntegerDivisionByZeroException { 
      print('Cannot divide by zero'); 
   } 
} 

Output:

Cannot divide by zero

Example: Using the catch Block :

In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime.

main() { 
   int x = 12; 
   int y = 0; 
   int res;  
   
   try {  
      res = x ~/ y; 
   }  
   catch(e) { 
      print(e); 
   } 
}

Output:

IntegerDivisionByZeroException

Leave a comment

Your email address will not be published. Required fields are marked *