Dart 断言(assert)和异常

一.断言(assert)

断言的作用是:如果表达式的求值结果不满足需要,则打断代码的执行。
可以要将提示消息附加到断言,添加一个字符串作为第二个参数。
实例:

void main()
{
	String urlString = 'http://www.baidu.com';
	assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".');
	// Failed assertion: 'urlString.startsWith('https')': URL (http://www.baidu.com) should start with "https"
	// 当urlString不是以https开头时,代码的执行会被打断
	// 当urlString是以https开头时,代码会继续执行
}

传入assert的参数,可以是任意表达式或者方法,只要返回值是bool就可以,当断言失败时(返回false),会抛出AssertionError异常。

注意:断言只有在检查模式下运行有效,在生产模式下是不会运行的。
二.异常

异常(或异常事件)是在执行程序期间出现的问题。发生异常时,程序的正常流程中断,程序/应用程序异常终止。
与Java相反,所有的dart异常都是未受检异常。也就是说当调用一个可以抛出异常的方法时,不必一定去捕获这个异常。这点和Kotlin一样,都是为了简化代码,增加可读性。如果你担心这段代码真的会产生什么异常,那么可以自行捕获。
Dart2的异常是Exception或者Error(包括它们的子类)的类型,甚至可以是非Exception或者Error类,也可以抛出,但是不建议这么使用。
Exception主要是程序本身可以处理的异常,比如:IOException。我们处理的异常也是以这种异常为主。
Error是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 DartVM出现的问题。比如:内存溢出(OutOfMemoryError)等等。

1. 抛出异常

throw关键字用于显式引发异常。应该处理引发的异常,以防止程序突然退出。
语法:

throw new Exception_name()

实例:

void test_age(int age)
{
	if(age<0)
	{
		throw new FormatException();
	}
}

main()
{
	try
	{
		test_age(-2);
	}
	catch(e)
	{
		print('Age cannot be negative'); 
	}
	// 执行结果:
	//Age cannot be negative
}
2. 捕获异常
(1) tryoncatch

try块嵌入可能导致异常的代码。需要指定异常类型时使用on块。当处理程序需要异常对象时使用catch块。
try块必须紧跟一个on/catch块或一个finally块(或两者之一)。当try块中发生异常时,控制将转移到catch
处理异常的语法如下:

try
{ 
   // code that might throw an exception 
}  
on Exception1
{ 
   // code for handling exception 
}  
catch Exception2
{ 
   // code for handling exception 
}
注意:
1. 代码段可以有多个on/catch块来处理多个异常
2. on块和catch块是相互包含的,即try块可以与on块和catch块相关联

使用on块实例:

void main()
{ 
	int x = 12; 
	int y = 0; 
	int res;  

	try
	{
		res = x ~/ y; 
	}
	on IntegerDivisionByZeroException
	{
		print('Cannot divide by zero'); 
	}

	// 直径结果:
	// Cannot divide by zero
}

使用catch块实例:

void main()
{ 
	int x = 12; 
	int y = 0; 
	int res;  

	try
	{
		res = x ~/ y; 
	}
	catch(e)
	{
		print(e);
	}

	// 直径结果:
	// IntegerDivisionByZeroException
}

on…catch块实例:

void main()
{ 
	int x = 12; 
	int y = 0; 
	int res;  

	try
	{
		res = x ~/ y; 
	}
	on IntegerDivisionByZeroException catch(e)
	{
		print(e);
	}

	// 直径结果:
	// IntegerDivisionByZeroException
}
(2) finally

finally块包括应该执行的代码,而不管异常的发生。try/on/catch之后无条件执行可选的finally块。
使用finally块的语法如下:

try
{ 
   // code that might throw an exception 
}  
on Exception1
{ 
   // code for handling exception 
}  
catch Exception2
{ 
   // code for handling exception 
}
finally
{ 
   // code that should always execute; irrespective of the exception 
}

finally块实例:

void main()
{ 
	int x = 12; 
	int y = 0; 
	int res;  

	try
	{
		res = x ~/ y; 
	}
	on IntegerDivisionByZeroException
	{
		print('Cannot divide by zero');
	}
	finally
	{
		print('Finally block executed');
	}

	// 直径结果:
	// Cannot divide by zero
	// Finally block executed
}
(2) rethrow

可以使用rethrow关键字,重新抛出异常,如:

void misbehave()
{
	try
	{
		dynamic foo = true;
		print(foo++); 		// Runtime error
	}
	catch (e)
	{
		print('misbehave() partially handled ${e.runtimeType}.');
		rethrow; 			// Allow callers to see the exception.
	}
}

void main()
{
	try
	{
		// 虽然 catch 了异常,但是又 rethrow 了,所以要捕获
		misbehave();
	}
	catch (e)
	{
		print('main() finished handling ${e.runtimeType}.');
	}

	// 执行结果;
	// misbehave() partially handled NoSuchMethodError.
	// main() finished handling NoSuchMethodError.
}
(3) 自定义异常

Dart中的每个异常类型都是内置类Exception的子类。Dart可以通过扩展现有异常来创建自定义异常。
定义自定义异常的语法:

class Custom_exception_Name implements Exception
{ 
   // can contain constructors, variables and methods 
}

实例:

class AmtException implements Exception
{
	String errMsg() => 'Amount should be greater than zero';
}

void withdraw_amt(int amt)
{
	if (amt <= 0)
	{
		throw new AmtException();
	}
}

void main()
{
	try
	{
		withdraw_amt(-1);
	}
	catch(e)
	{
		print(e.errMsg());
	}
	finally
	{
		print('Ending requested operation.....');
	}
	// 执行结果: 
	// Amount should be greater than zero
	// Ending requested operation.....
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值