异常是发生在程序内部的错误。当程序内部发生异常时,程序的正常流程被中断并异常终止,并显示错误和异常堆栈作为输出。因此,必须注意异常以防止应用程序终止。
Dart的内置异常:
Drat 中的每个内置异常都属于一个名为Exception的预定义类。为了防止程序出现异常,我们在Dart使用了try/on/catch 块。
try {
// program that might throw an exception
}
on Exception1 {
// code for handling exception 1
}
catch Exception2 {
// code for handling exception 2
}
示例 1:在dart使用试穿块。
Dart
void main() {
String geek = "GeeksForGeeks";
try{
var geek2 = geek ~/ 0;
print(geek2);
}
on FormatException{
print("Error!! \nCan't act as input is not an integer.");
}
}
Dart
void main() {
String geek = "GeeksForGeeks";
try{
var geek2 = geek ~/ 0;
print(geek2);
}
catch(e){
print(e);
}
}
Dart
void main() {
int geek = 10;
try{
var geek2 = geek ~/ 0;
print(geek2);
}
catch(e){
print(e);
}
finally {
print("Code is at end, Geek");
}
}
Dart
// extending Class Age
// with Exception class
class Age implements Exception {
String error() => 'Geek, your age is less than 18 :(';
}
void main() {
int geek_age1 = 20;
int geek_age2 = 10;
try{
// Checking Age and
// calling if the
// exception occur
check(geek_age1);
check(geek_age2);
}
catch(e){
// Printing error
print(e.error());
}
}
// Checking Age
void check(int age){
if(age < 18){
throw new Age();
}
else
{
print("You are eligible to visit GeeksForGeeks :)");
}
}
输出:
Error!!
Can't act as input is not an integer.
示例 2:在dart使用 try-catch 块。
Dart
void main() {
String geek = "GeeksForGeeks";
try{
var geek2 = geek ~/ 0;
print(geek2);
}
catch(e){
print(e);
}
}
输出:
Class 'String' has no instance method '~/'.
NoSuchMethodError: method not found: '~/'
Receiver: "GeeksForGeeks"
Arguments: [0]
最终块: dart的最后一块用于包含必须执行的特定代码,而不考虑代码中的错误。尽管如果包含 finally 块是可选的,那么它应该在 try 和 catch 块结束之后。
finally {
...
}
例子:
Dart
void main() {
int geek = 10;
try{
var geek2 = geek ~/ 0;
print(geek2);
}
catch(e){
print(e);
}
finally {
print("Code is at end, Geek");
}
}
输出:
Unsupported operation: Result of truncating division is Infinity: 10 ~/ 0
Code is at end, Geek
与其他语言不同,在Dart中可以创建自定义异常。为此,我们在dart使用throw new关键字。
示例:在dart创建自定义异常。
Dart
// extending Class Age
// with Exception class
class Age implements Exception {
String error() => 'Geek, your age is less than 18 :(';
}
void main() {
int geek_age1 = 20;
int geek_age2 = 10;
try{
// Checking Age and
// calling if the
// exception occur
check(geek_age1);
check(geek_age2);
}
catch(e){
// Printing error
print(e.error());
}
}
// Checking Age
void check(int age){
if(age < 18){
throw new Age();
}
else
{
print("You are eligible to visit GeeksForGeeks :)");
}
}
输出:
You are eligible to visit GeeksForGeeks :)
Geek, your age is less than 18 :(