Learn Exception Handling in Dart Programming

Exception handling makes it possible for you to handle and recover from errors that may occur during the execution of your code. Dart offers try-catch blocks as a mechanism for handling and catching exceptions.

In Dart, each exception is a subtype of the already-defined class Exception. To avoid an abrupt programme shutdown, exceptions must be managed.


Built-in Exceptions in Dart

DeferredLoadException

When a deferred library cannot load, an exception is thrown.

FormatException

Exception that cannot be parsed or handled when a string or other data does not have the expected format.

IntegerDivisionByZeroException

Thrown when a number is divided by zero.

IOException

Base class for all exceptions related to Input-Output.

IsolateSpawnException

When an isolate cannot be constructed, an exception is thrown.

Timeout

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

try/on/catch blocks in Dart

Try blocks include code that could potentially throw an exception. When a specific exception type must be declared, the on block is used. When the handler need the exception object, it uses the catch block.

Syntax

try {

   // program that might throw an exception

on Exception1 {

   // code for handling exception 1

catch Exception2 {

   // code for handling exception 2

}

Example: Using a try-on block in the dart 

void main() {

  String x = "Test";

  try{

    var y = x ~/ 0;

    print(y);

  }

  on FormatException {

    print("Error!");

  }

}

Example: Using a try-catch block in the dart

void main() {

  String x = "Test";

  try{

    var y = x ~/ 0;

    print(y);

  }

  catch(e){

    print(e);

  }

}

The Finally Block

Regardless of whether an exception occurs, the finally block contains code that must be run. Try/on/Catch is followed by an unconditional execution of the optional finally block.

Syntax

try {

   // code that might throw an exception

} 

on Exception1 {

   // exception handling code

} 

catch Exception2 {

   //  exception handling

} 

finally {

   // code that should always execute; irrespective of the exception

}

Example

try {

  xyz();

} catch (e) {

  print(e); // Handle the exception

} finally {

  clean();

}

 

By using try-catch blocks, you can gracefully handle exceptions in your Dart code and provide appropriate error messages or perform recovery actions when necessary.

Post a Comment

If you have any questions or concerns, please let me know.

Previous Post Next Post