Exception Handling in Dart

Exception In Dart

An exception is an error that occurs at a runtime during program execution. When the exception occurs, flow of the program is interrupted and the program terminates abnormally. There is a high chance of crashing or terminating the program when an exception occurs. Therefore, to save from crashing, you need to catch the exception.

Syntax

try {
    
// Your Code Here
  }
catch(ex){
// Exception here
}

Try / Catch / On / Finally In Dart

Try

You can write the logical code that creates exceptions in the try block.

Catch

When you are uncertain about what kind of exception is produced by a program then a catch block is used. It is written with a try block to catch the general exception.

On

On block is used, when you know what types of exception are produced by the program.

Example

void main() {   
   int a = 18;   
   int b = 0;   
   int res;    
     
   try {    
      res = a ~/ b;   
   }    
    // It returns the built-in exception related to the occurring exception  
   catch(ex) {   
      print(ex);   
    }   
}  
Show Output

Finally

The finally block is always executed whether the exceptions occur or not. It is optional to include the final block but if it is included it should be after the try and catch block is over.

Syntax

try {
.....
}
on Exception1 {
....
}
catch Exception2 {
....
}
finally {
// code that should always execute; whether exception or not.
}

Example

void main() {
  int a = 12;
  int b = 0;
  int res;

  try {
    res = a ~/ b;
    // ignore: deprecated_member_use
  } on IntegerDivisionByZeroException {
    print('Cannot divide by zero');
  }

  print('Finally block always executed');
}
Show Output

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 unexpectedly.

Syntax

throw new Exception_name() 

Example

void main() {
  try {
    check_account(-10);
  } catch (e) {
    print('The account cannot be negative');
  }
}

void check_account(int amount) {
  if (amount < 0) {
    throw new FormatException(); // Raising explanation externally
  }
}
Show Output

Why Is Exception Handling Needed?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. Therefore, exceptions must be handled to prevent the application from unexpected termination.

Why Error Handling Is Needed?

  • To avoid abnormal termination of the program.
  • To avoid an exception caused by logical error.
  • To avoid the program from falling apart when an exception occurs.
  • To reduce the vulnerability of the program.
  • To maintain a good user experience.
  • To try providing aid and some debugging in case of an exception.