Dart Exceptions : Throw Keyword | Writing Custom Exceptions

Dart Exceptions : Throw Keyword | Writing Custom Exceptions

·

1 min read

Throw Keyword :

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

  • Syntax :

  •     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(); 
   } 
}

Custom Exception :

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

  • Syntax :

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

  •      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(); 
         } 
      }