📜  Dart – 异常类型

📅  最后修改于: 2021-09-02 05:32:17             🧑  作者: Mango

异常是一种运行时不需要的事件,它会中断代码执行流程。它可能是由于程序员的错误或错误的用户输入而发生的。在运行时处理此类事件称为异常处理。例如:- 当我们尝试访问空列表中的元素时。 Dart异常是运行时错误。它在程序执行时引发。

Dart的内置异常:

下表列出了主要的dart例外情况。

Sr.  Exceptions Description
1 DefferedLoadException It is thrown when a deferred library fails to load.
2 FromatException  It is the exception that is thrown when a string or some other data does not have an expected format
3 IntegerDivisionByZeroException It is thrown when the number is divided by zero.
4 IOEException It is the base class of input-output-related exceptions.
5 IsolateSpawnException It is thrown when an isolated cannot be created.
6 Timeout It is thrown when a scheduled timeout happens while waiting for an async result.

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. Try:在try块中,我们编写可以产生异常的逻辑代码
  2. Catch: Catch块写有try块,用于捕获一般异常:也就是说,如果不清楚会产生什么样的异常。使用捕获块。
  3. On:当100%确定会抛出什么样的异常时,使用On块。
  4. 最后:最后一部分总是被执行,但不是强制性的。

示例 1:在dart使用试穿块。

Dart
// importing dart:io file 
import 'dart:io'; 
  
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); 
        }
    
        // It returns the built-in exception
        // related to the occurring exception  
        catch(e){ 
            print(e); 
        } 
}


Dart
void main() { 
    String geek = "GeeksForGeeks"; 
    try{ 
        var geek2 = geek ~/ 0; 
        print(geek2); 
    } 
    on FormatException catch(e) {
   
        print("Error!! \nCan't act as input is not an integer."); 
    } 
}


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."); 
    } 
      finally { 
        print("Code is at end, Geek"); 
      }     
    
}


Dart
void main() {   
   try {   
      geek(-5);   
   }   
   catch(e) {   
      print('The marks cannot be negative');   
   }   
}    
void geek(int div2) {   
   if(div2<0) {   
      throw new FormatException();  // Raising explanation externally  
   }   
}


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.

解释:

在上面的代码中,我们在 main()函数声明了两个变量 geek 和 geek2 。我们在 try 块中编写了可疑代码,将 x 除以可能引发异常的 0。 try 块发现错误,控制转移到具有处理错误的代码的块。通过使用它,程序并没有停止执行。

示例 2:在dart使用try-catch块。

Dart

void main() { 
    String geek = "GeeksForGeeks"; 
        try{ 
            var geek2 = geek ~/ 0; 
            print(geek2); 
        }
    
        // It returns the built-in exception
        // related to the occurring exception  
        catch(e){ 
            print(e); 
        } 
}

输出:

Class 'String' has no instance method '~/'.
NoSuchMethodError: method not found: '~/'
Receiver: "GeeksForGeeks"
Arguments: [0]

示例 3 :在dart使用on…catch块。

Dart

void main() { 
    String geek = "GeeksForGeeks"; 
    try{ 
        var geek2 = geek ~/ 0; 
        print(geek2); 
    } 
    on FormatException catch(e) {
   
        print("Error!! \nCan't act as input is not an integer."); 
    } 
}

输出:

FormatException

最终块:

dart的最后一个块用于包含必须执行的特定代码,而不管代码中是否有错误。尽管如果包含finally 块是可选的,那么它应该在 try 和 catch 块结束之后。

Syntax:
try {   
  .....  
}    
on Exception1 { 
  ....  
}    
catch Exception2 {  
  ....
}    
finally {   
   // code that should always execute; whether exception or not.  
}  

例子:

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."); 
    } 
      finally { 
        print("Code is at end, Geek"); 
      }     
    
}

输出:

Error!! 
Can't act as input is not an integer.
Code is at end, Geek

抛出异常

throw 关键字用于显式引发异常。 Dart提供了许多可以手动抛出的内置异常类。

Syntax: throw new Exception_name()  

例子:

Dart

void main() {   
   try {   
      geek(-5);   
   }   
   catch(e) {   
      print('The marks cannot be negative');   
   }   
}    
void geek(int div2) {   
   if(div2<0) {   
      throw new FormatException();  // Raising explanation externally  
   }   
}  

输出:

The marks cannot be negative

在上面的程序中,我们在 try 块中包装了 geek(-5) 语句,因为它可以抛出异常。

自定义异常

每个异常类都继承自 Exception 类。 Dart可以通过扩展现有异常来创建自定义异常。

Syntax: class Custom_exception_Name implements Exception { }   

示例:在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 

在上面的示例中,我们创建了一个自定义异常 Age。如果输入的金额不在例外范围内,代码会引发异常,我们将函数调用包含在 try…catch 块中。