Exceptions and how to handle exceptions in Dart

Exceptions in dart :

Exceptions are runtime errors. During program execution, if any unexpected happens, an exception is thrown. If you don’t have any handling for the exception, the program will crash. All exceptions in dart are unchecked exceptions i.e. they are not checked at compile time. The program will only check and throw it at runtime.

You can create your own exception but dart provides a couple of commonly used exceptions. All exceptions are implemented from Exception class. Following are the inbuilt exceptions :

DeferredLoadException : It is thrown when a deferred library fails to load

FormatException : Thrown for formatting related issues like the program is unable to parse a string etc.


IntegerDivisionByZeroException : Thrown if you are trying to divide one integer by zero. IOException : IO exceptions.

IsolateSpawnException : Thrown when an isolate can’t be created

TimeoutException : Thrown on async call timeout

These are the basic exception classes. Let me show you one example :

main() {
  int value = 100~/0;
  print(value);
}

This program will throw one IntegerDivisionByZeroException :

Unhandled exception:
IntegerDivisionByZeroException
#0      int.~/ (dart:core-patch/integers.dart:22:7)
#1      main (file:///Users/cvc/Documents/sample-programs/dart/example.dart:2:18)
#2      _startIsolate. (dart:isolate-patch/isolate_patch.dart:305:19)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)

Note that 100/0 is not an integer division. It will print Infinity. This exception is thrown only for integer division.

Handling exceptions : try-catch :

try-catch block is used for handling exceptions. The main code is written in the try block. If an exception occurs, it will execute the code in the catch block. The program execution will not stop if you use try-catch.

import 'dart:io';

main() {
  try {
    print("Enter a number : ");
    var inputStr = stdin.readLineSync();
    int value = int.parse(inputStr);
    print(value);
  } catch (e) {
    print(e);
  }
  print("End of main block...");
}

In this example, the program is asking the user to enter a number. It reads that number and stores it in inputStr variable. We are using int.parse to parse the integer number from the variable inputStr. If it can’t parse, it will throw one FormatException.

Dart exception try catch

If the parsing fail, it throws FormatException, but the program execution doesn’t stop.

Handling exceptions : try, on, catch :

on block is used to specifically catch one exception. It is used as on exceptionName. Note that catch block can be used with on block and multiple on block can be used one after another.

import 'dart:io';

main() {
  try {
    print("Enter a number : ");
    var inputStr = stdin.readLineSync();
    int value = int.parse(inputStr);
    print(value~/0);
  } on FormatException{
    print("FormatException. Please enter a number.");
  } on IntegerDivisionByZeroException{
    print("IntegerDivisionByZeroException");
  }catch (e) {
    print(e);
  }
  print("End of main block...");
}

For this example, if the input is a number, it will throw one IntegerDivisionByZeroException and if the input is not a number, it will throw FormatException. Example output :

Enter a number : 
12
IntegerDivisionByZeroException
End of main block...

Enter a number : 
kj
FormatException. Please enter a number.
End of main block...

finally block :

finally block runs always. It will run always after the try block irrespective of any exception. finally block is useful if you want to close/execute something always. The syntax for finally is as below :

try{
	// code for try
}on Exception1{
	// code for Exception1
}catch Exception{
	// code for catch
}finally{
	// code for finally block
}

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Don't forget to subscribe ❤️❤️🤩