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');
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/p/17221480.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇