We have already seen automated exception which catch by direct compiler and we store this exception in one variable than print the exception.
Now , we will see how we can create custom exceptions in dart using throw keyword.
void main()
{
try{
numberCheck(15263);
}
catch(e)
{
print("Please enter digit nummber");
}
}
void numberCheck(var number)
{
if(number.toString().length == 5)
{
print("Valid Number");
}
else
{
throw FormatException();
}
}
When our condition is true at that time we receive this type of output.
When our condition is not true at that time we receive this type of output.
Now ,we make our custom exception for error handling .
For making custom exception handle first we have to create one class then implements Exception on this class. Exception is default class in dart so we can directly implements to it.
After that we have to pass our Exception in " on " , if we pass our ageException in direct catch at that time we can face error.
void main()
{
try{
ageCheck(15);
} on ageException catch (e){
print(e.errorMessage());
} catch(e) {
print(e);
}
}
class ageException implements Exception{
String errorMessage()
{
return "Oops!!!! , Sorry , you can not send message";
//return this.errorMessage();
}
}
void ageCheck(int age)
{
if (age <18)
{
throw ageException();
}
else{
print("You can send message");
}
}
When our condition is true at that time we receive this type of output.
When our condition is not true at that time we receive this type of output.