Dart Exceptions

 

Dart Exceptions

Dart Exceptions are the run-time error. It is raised when the program gets execution. The program doesn't report the error at compile time when the program runs internally and if Dart compiler found something not appropriate. Then, it reports run-time error and the execution of program is terminated abnormally. This type of error is called Exceptions. For example - A given number is divided by the zero or we try to access the elements from the empty list.

Dart supports the following types of built-in exceptions.

Sr.ExceptionsDescription
1.DefferedLoadExceptionIt is thrown when a deferred library fails to load.
2.FromatExceptionIt is the exception which is thrown
3.IntegerDivisionByZeroExceptionIt is thrown when number is divided by zero.
4.IOEExceptionIt is the base class of input-output related exception.
5.IsolateSpawnExceptionIt is thrown when an isolated cannot be created.
6.TimeoutIt is thrown when a schedule timeout happens while waiting for an async result.

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.

The syntax of exceptional handling is the given below.

Syntax:

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

One should remember the following points.

  • We can handle the multiple exceptions using the more than one catch block.
  • The on block and the catch block is mutually inclusive that means we can associate the both - the on block and catch block with the try block.

In the following example, the variable x is divided by the y variable respectively. The code is thrown when it tries to divide by the zero. The on block consists of the code to handle the exception. Let's understand the following code.

Example - Using the on block

  1. void main() {   
  2.    int x = 12;   
  3.    int y = 0;   
  4.    int res;    
  5.      
  6.    try {  
  7.       res = x ~/ y;   
  8.    }   
  9.    on IntegerDivisionByZeroException {   
  10.       print('Cannot divide by zero');   
  11.    }   
  12. }  

Output

Cannot divide by zero

Explanation:

In the above code, we declared the three variable x, y and res in main () function. We written the suspect code in try block divided the x by the 0 that might be thrown an exception. The try block found the error the control transferred to the on block that has the code to handle the error. By using this, the program did not stop its execution.

Let's understand the following example using the catch block.

Example - Using the catch Block

  1. void main() {   
  2.    int x = 12;   
  3.    int y = 0;   
  4.    int res;    
  5.      
  6.    try {    
  7.       res = x ~/ y;   
  8.    }    
  9. // It returns the built-in exception related to the occurring exception  
  10.    catch(E) {   
  11.       print(E);   
  12.    }   
  13. }  

Output

IntegerDivisionByZeroException

Now look at the example of on…catch block together

Example 3: on…catch block

  1. void main() {   
  2.    int x = 12;   
  3.    int y = 0;   
  4.    int res;    
  5.      
  6.    try {   
  7.       res = x ~/ y;   
  8.    }    
  9.    on IntegerDivisionByZeroException catch(E) {   
  10.       print(E);   
  11.    }   
  12. }  

Output

IntegerDivisionByZeroException

The Finally Block

The finally block always executes whether there is exception occur or not. It executes unconditionally after the try/on/catch.

The syntax of finally block is given below.

Syntax -

  1. try {   
  2.    // code that may be throw an exception   
  3. }    
  4. on Exception1 {   
  5.    // exception handling code or specifying the exception  
  6. }    
  7. catch Exception2 {   
  8.    //  code for exception handling   
  9. }    
  10. finally {   
  11.    // code that should always execute; whether exception or not.  
  12. }  

Let's understand the following example of finally block.

Example -

  1.    finally { void main() {   
  2.    int x = 12;   
  3.    int y = 0;   
  4.    int res;    
  5.      
  6.    try {   
  7.       res = x ~/ y;   
  8.    }   
  9.    on IntegerDivisionByZeroException {   
  10.       print('Cannot divide by zero');   
  11.    }   
  12.   
  13.       print('Finally block always executed');   
  14.    }   
  15. }  

Output

Cannot divide by zero 
Finally block executed

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:

  1. throw new Exception_name()  

Let's understand the following example.

Example -

  1. main() {   
  2.    try {   
  3.       check_marks(-10);   
  4.    }   
  5.    catch(e) {   
  6.       print('The marks cannot be negative');   
  7.    }   
  8. }    
  9. void check_marks(int marks) {   
  10.    if(marks<0) {   
  11.       throw new FormatException();  // Raising explanation externally  
  12.    }   
  13. }  

Output

The marks cannot be negative

Custom Exceptions

As we discussed above, each of the exception in dart is the subtype of the built-in class Exception. Dart provide the flexibility to create custom exception by extending the existing exception class. The syntax is given below.

Syntax: Defining the Exception

  1. class Custom_exception_Name implements Exception {   
  2.    // can contain constructors, variables and methods   
  3. }   

Let's understand the following code.

Example -

  1. class AmtException implements Exception {   
  2.    String expMsg() => 'Entered Amount should be greater than zero';   
  3. }    
  4. void main() {   
  5.    try {   
  6.       withdraw_amt(-1);   
  7.    }   
  8.    catch(E) {   
  9.       print(E.expMsg());   
  10.    }    
  11.    finally {   
  12.       print('Ending requested operation.....');   
  13.    }   
  14. }    
  15. void withdraw_amt(int amt) {   
  16.    if (amt <= 0) {   
  17.       throw new AmtException();   
  18.    }   
  19. }    

Output

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

Explanation:

In the above example, we created a custom exception, AmtException. The code raised the exception if the entered amount is not within the excepted range and we enclosed the function invocation in the try…catch block

Comments