Dart Exception Handling (Flutter)

Dart Exception Handling (Flutter)

An exception is an error that takes place inside the program. When an exception occurs inside a program the normal flow of the program is disrupted and it terminates abnormally, displaying the error and exception stack as output. So, an exception must be taken care to prevent the application from termination.

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 to when we require specifying the exceptions. The catch block is used to when handler needs the exception object.

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

Syntax:

try {
// code that might throw an exception
}
on Exception1 {
// Specify the exception
}
Catch Exception2 {
// code for handling exception
}

Example: Using the ON Block

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

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

It should produce the following output

Cannot divide by zero

Example: Using the catch Block

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try {  
      res = x ~/ y; 
   }  
   catch(e) { 
      print(e); 
   } 
}

It should produce the following output

IntegerDivisionByZeroException

Example: on…catch

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try { 
      res = x ~/ y; 
   }  
   on IntegerDivisionByZeroException catch(e) { 
      print(e); 
   } 
}

It should produce the following output

IntegerDivisionByZeroException

The Finally Block

The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch.

The syntax for using the finally block is as follows −

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 :- FINALLY

main() { 
   int x = 12; 
   int y = 0; 
   int res;  

   try { 
      res = x ~/ y; 
   } 
   on IntegerDivisionByZeroException { 
      print('Cannot divide by zero'); 
   } 
   finally { 
      print('Finally block executed'); 
   } 
}

It should produce the following output

Cannot divide by zero 
Finally block executed

Throwing an Exception

The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.

The syntax for raising an exception explicitly is −

throw new Exception_name()

Example

main() { 
   try { 
      test_age(-2); 
   } 
   catch(e) { 
      print('Age cannot be negative'); 
   } 
}  
void test_age(int age) { 
   if(age<0) { 
      throw new FormatException(); 
   } 
}

It should produce the following output

Age cannot be negative

Custom Exceptions

As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below −

Syntax: Defining the Exception

class Custom_exception_Name implements Exception { 
   // can contain constructors, variables and methods 
}

Custom Exceptions should be raised explicitly and the same should be handled in the code.

Example

class AmtException implements Exception { 
   String errMsg() => 'Amount should be greater than zero'; 
}  
void main() { 
   try { 
      withdraw_amt(-1); 
   } 
   catch(e) { 
      print(e.errMsg()); 
   }  
   finally { 
      print('Ending requested operation.....'); 
   } 
}  
void withdraw_amt(int amt) { 
   if (amt <= 0) { 
      throw new AmtException(); 
   } 
}

In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try...catch block.

The code should produce the following output

Amount should be greater than zero 
Ending requested operation....

THANK YOU!