Flutter之异常处理

Flutter之异常处理

一、前言:

flutter的异常处理与java非常相似。与java不同的是Dart不检测是否是声明的,也就是说方法或者函数不需要声明要抛出哪些异常

二、抛出异常的三种方式
void textException(){
	throw Exception("方式一");
}
void textException(){
	throw ("方式二");
}
void textException()=>throw ("方式三");
三、异常捕获格式
try{
//逻辑代码块
}catch(e,r){
//处理代码块
}
//try:如果try语句中发生异常那么相应的异常对象就会被抛出,
//处理后就会跳过try语句块中剩下的执行内容,从catch语句的第一条开始执行

//e:异常对象

//r:StackTrace对象说白了就是更详细的打印出异常信息的位置

举例

void textException()=>throw ("异常抛出");
try {
textException();
}catch(e,r){
print(e.toString());
print(r.toString());
}
四、try-on-catch语句

如果try代码块中有许多语句就会发生异常,而且发生异常的种类很多,那么可以使用on关键字,on关键字可以捕获到某种异常,但是获取不到异常对象
举例

void textException(){
	throw Exception("这是一个Exception异常");
}
void FormatException(){
	throw Exception("这是一个FormatException异常");
}
try{
textException();
}on FormatException catch(e){
print(e.toString());
}catch(e,r){
print(e);
}
五、重新抛出异常

在捕获异常中,同时允许继续传播,使用rethrow关键字,重置堆栈跟踪到最后抛出位置

举例

void textException(){
	throw Exception("这是一个Exception异常");
}
try{
	text();
}catch(e,r){
print(e.toString());
}
void text(){
	try{
	textException();
	}catch(e){
	print(e.toString());
	rethrow;
	}
}

结果

 Exception("这是一个Exception异常");
 Exception("这是一个Exception异常");
六、finally语句

无论是否有异常都会执行,例如网络连接,数据库链接和打开链接在完成使用后需要释放资源

举例

try{}catch(e){}finally{}
六、自定义异常

以http请求异常为例

enum StatusType{
	DEFAULT,
	STATUS_404,
	STATUS_500
}
void main(){
	httpResponse();
}
class StatusExpection implements Exception{
	StatusType type;
	String msg;
	StatusExpection ({StatusType.DEFAULT,msg});
	String toString(){
		return msg??"http请求异常";
	}
}
Future httpResponse() async{
try{
	var url = "httpxxxx";
	http.get(url).then((res){
	print("${res.statusCode}");
	if(res.statusCode == 200){
	return response;
	}else if(res.statusCode == 404){
	throw StatusExpection(type:StatusType.STATUS_404,msg:"找不到页面");
	}else if(res.statusCode == 500){
	throw StatusExpection(type:StatusType.STATUS_500,msg:"服务器内部错误");
	}
})
	}catch(e,r){
	print(e);
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可可鸭~

想吃糖~我会甜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值