Dart 异常

异常

抛出异常

抛出异常的方式有3种

fun()=>throw "error";//胖箭头方法
//普通方法
fun(){
    throw "error";
}
//普通方法
fun(){
    throw Exception("error");
}

重新抛出 rethrow

将异常捕获后重新抛出,该关键字仅限用于try...catch...结构中

main(List<String> args) {
  try{
    fun();
  } catch(e,r){
    print(e);
    print(r);
  }
}
fun(){
  try{
    fun2();
  } on Exception catch(e,r){
    rethrow;//重新抛出异常
  } finally{
    print('最终无论如何都会执行!');
  }
}
fun2()=>throw Exception('fun2');

捕获异常

Dart捕获的异常有两个参数:e异常对象,r 异常堆栈

main(List<String> args) {
	try {
    	fun();
	} catch (e,r){
    	print(e);
    	print(r);
  	}
}
fun(){
    throw "Error";
}
按异常类型捕获
try{
    /*code*/
} on FormatException catch (e,r){
	/*code*/
} on IOException catch (e,r){
    /*code*/
} catch(e,r) {
    /*code*/
}

最后必执行:finally

try{
    /*code*/
} on FormatException catch (e,r){
	/*code*/
} on IOException catch (e,r){
    /*code*/
} catch(e,r) {
    /*code*/
} finally {
    print("无论成功与否,都会执行");
}

自定义异常

实现接口Exception,重写方法toString()

class MyExecption implements Exception {
    final String message;
    MyExecption(this.message);
    //重写toString方法
    @override
    String toString() => message.isNotEmpty ? message:'MyExecption';
}

调用(这里只是举个例子)

main(List<String> args) {
  try{
    fun();
  }catch(e,r){
    print(e.toString());
    print(r);
  }
}
fun()=>throw MyExecption('my message');
posted @ 2023-03-16 10:47  勤匠  阅读(63)  评论(0编辑  收藏  举报