![]() |
VOOZH | about |
An exception is an error that occurs 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 of to prevent the application from terminating.
Built-in Exceptions in Dart:
👁 Built-in Exceptions in Dart:
Every built-in exception in Dart comes under a pre-defined class named Exception. To prevent the program from exception, we make use of try/on/catch blocks in Dart.
try {
// program that might throw an exception
}
on Exception1 {
// code for handling exception 1
}
catch Exception2 {
// code for handling exception 2
}
Example :
Output:
Error!!
Can't act as input is not an integer.
Example :
Output:
Class 'String' has no instance method '~/'.
NoSuchMethodError: method not found: '~/'
Receiver: "GeeksForGeeks"
Arguments: [0]
Final block: The final block in dart is used to include specific code that must be executed irrespective of error in the code. Although it is optional to include finally block if you include it then it should be after try and catch block are over.
finally {
...
}
Example:
Output:
Unsupported operation: Result of truncating division is Infinity: 10 ~/ 0
Code is at end, Geek
Unlike other languages, in Dart to one can create a custom exception. To do, so we make use of throw new keyword in the dart.
Example:
Output:
You are eligible to visit GeeksForGeeks :)
Geek, your age is less than 18 :(