What is exception handling in DART
In this article, i am going to explain about exception handling in DART language.
Exception Handling in DART language
DART is designed to facilitate handling of error condition using the same mechanism, based on exception, that is employed by java and C++. A exception is an event that occur during the execution of program.
In order to deal with possible error condition you will normally divide the relevant part of your program into a number of blocks of three different types:
- Try block
Try block contain code that forms part of normal operation of your program, but which might encounter some serious error conditions.
- Catch block
Catch block are used to handling the exception.
- Finally block
It is reside at the end of the try block, and it's executed whether error is occurred or not.
Here, some of common built-in DART exception:
- IndexOutOfRangeException:
If you declare a list of size 4 (four) and wants to access it's fifth (5) element, then it gives IndexOutOfRangeException:5.
- NoSuchMethodException
If you want to access that method which is not given in your code, then NoSuchMethodException:method is found :'Method name' exception is occured.
- NullPointerException
NullPointerException is occurred, when you gives a null value to any variable and wants to perform some operation by the help of this variable.
Example of exception handling in DART language
void main() {
var list = [1,2,3,4];
/**** IndexOutOfRangeException *********/
try{
print("Out of range execption................");
print(" ");
print(list[5]); //Try to access out of range variable.
}
catch(IndexOutOfRangeException ex){
print('The exception is: ${ex}');
}
/**** NoSuchMethodException *********/
try{
print("");
print("No such method exception................");
print("");
MethodExcep obj = new MethodExcep();
obj.IllegalMethod(); // you'r trying to access that method,which is not aviable.
}
catch(NoSuchMethodException ex){
print('The exception is: ${ex}');
}
/**** NullPointerException*********/
try{
print("");
print("Null pointer exception................");
print("");
MethodExcep o = new MethodExcep();
o.a(null,2); // You want to perform operation on null value.
}
catch(NullPointerException ex){
print('The exception is: ${ex}');
}
finally{
print("All Exception all handled here");
}
}
class MethodExcep{
void Legal(){
print("I am a legal method");
}
a(int a, int b)
{
int c=a-b;
print(c);
}
}
|
Output:
Ask Your Question
Got a programming related question? You may want to post your question here