Dart Exceptions : Throw Keyword | Writing Custom Exceptions
Jeet Bhalu
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(); } }
0
Subscribe to my newsletter
Read articles from Jeet Bhalu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Dart#dart language#dart-for-beginnersdart programming tutorial#dart-keywordsDevOps Journey#DevopscommunityDevopsDeveloperDevops articlesdevelopmentdevOpen SourceObject Oriented ProgrammingProgramming Blogs
Written by
Jeet Bhalu
Jeet Bhalu
i am Jeet Bhalu i am flutter App developer