Exception Handling in Dart

When the normal flow of the program is disrupted an exception occurs in dart.Dart Exceptions are the run-time error. It is raised when the program gets executed. The program doesn't report the error at compile time when the program runs internally and if the Dart compiler found something not appropriate. Then, it reports run-time error and the execution of the program is terminated abnormally. This type of error is called Exceptions.

The main objective of the exception is to handle the run-time error and prevent the program from terminating abruptly. Every exception in the Dart is a subtype of the pre-defined class Exception. Dart provides the following techniques to handle the exceptions.

The try/on/catch Blocks

The try block is used to hold the block of code that might be thrown an exception. The on block is used when we require specifying the exceptions. The catch block is used when the handler needs the exception object.

If the try block finds the error, it throws it to the catch block and the catch block has the code to handle the error. The try block must be followed by exactly one block either on/ catch or one finally block.

The syntax of exceptional handling is given below.

Syntax:

  • Using try-catch
    try { await foo(); } on Exception catch (e) { print(e); // Only catches an exception of type `Exception`. } catch (e) { print(e); // Catches all types of `Exception` and `Error`. }
  • Use catchError
    await foo().catchError(print);

try { 

   // code that might throw an exception 

}  

on Exception1 { 

   // code for handling exception 

}  

catch Exception2 { 

   // code for handling exception 

}

 

The Finally Block

The finally block always executes whether an exception occurs or not. It executes unconditionally after the try/on/catch.

The syntax of finally block is given below.

Syntax -

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.  

}  

Let's understand the following example of finally block.

Example - 

finally { void main() {   

  int x = 12;   

  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.

Exception occured

Throwing an Exception

We can raise an exception explicitly or forcefully. The explicitly raised exception should be handled to avoid the program from existing sharply. The syntax is given below.

Syntax:

  • throw new Exception_name()  

Let's understand the following example.

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

 

Try, catch blocks and throw exceptions by throw keyword

 

main(List<String> args) {

  divide(10, 0);

divide(int a, int b) {

  if (b == 0) {

    throw new IntegerDivisionByZeroException();

  }

  return a / b;

}

 

Let’s catch the exception pass catch block

 

main(List<String> args) {

  try {

    divide(10, 0);

  } on IntegerDivisionByZeroException {

    print('Division by zero.');

  }

}

divide(int a, int b) {

  if (b == 0) {

    throw new IntegerDivisionByZeroException();

  }

  return a / b;

}


Advertisements