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方法
    
    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 @   勤匠  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇
点击右上角即可分享
微信分享提示