Dart Learn Notes 04
2024-09-01 18:31:52
流程控制语句
流程控制语句的作用就是控制代码的执行流程。
if and else
var a = 10;
if(a > 10){
print('ok');
}else if( 5 < a <=10 ){
print('soso');
}else{
print('not ok');
}
for循环
var list = [];
for(int i = 0; i<10; i++){
list.add(i);
}
list.forEach((item) => print(item));
for (var item in list) {
print(item);
}
三种循环方式,写起来有一种在写java代码的感觉,不得不说,为了google为了照顾广大的android程序员确实在dart的语法上特别亲和。
while and do-while
int a = 3;
while(a > 0){
print(a);
a--;
}
do{
print(a);
a--;
}while(a > 0);
区别就是do-while会先执行一次。
break and continue
for(int a = 0; a < 9 ;a ++){
if(a == 3){
break;
}
print(a);
}
for(int a = 0; a < 9 ;a ++){
if(a == 3){
continue;
}
print(a);
}
break 是到达条件的时候循环就不执行了,continue是到达条件的时候本次不执行,下次执行。
switch and case
var type = 2;
switch(type){
case 1:
print('top');
break;
case 2:
print('2th');
break;
default:
print('default');
}
需要注意java中如果条件后不加break,很可能会造成switch的case穿透。但是在dart中不会,因为如果不写break,运行就会报错。在Dart中,Switch的case条件下,要么执行语句和break都写,要么都不写,违反规则,dart会让程序直接报错。
断言
assert会在运行时判断条件是否成立,如果条件不成立,会抛出异常。
assert( a > 10);
异常
throw
Dart中允许抛出异常,异常有两种,Error,Exception,但是使用 throw 抛出异常的时候,不限于这两种异常及其子类,你甚至可以直接抛出一个对象。和Java不同,dart中是非检查异常,而且,它没有throws这个关键字,不能用throws在方法上直接抛异常。
throw new FormatException('Expected at least 1 section');
throw 'this is a Exception';
catch
捕获异常,进行处理
try{
method();
}on Exception catch (e){
print(e);
}
finally
如果要保证捕获到异常后仍然要执行后续代码,使用finally
try{
method();
}on Exception catch (e){
print(e);
}finally{
print('finally');
}
最新文章
- 【番外篇】ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6)
- OpenCV2:特征匹配及其优化
- Matlab绘图详解
- 佛祖保佑 永无BUG 永不修改
- 使用SignalR+Asp.net创建实时聊天应用程序
- Apple的App Analytics统计平台你必须知道的Q&;A整理与翻译
- 在qq中可以使用添加标签功能
- public View getView(int position, View convertView, final ViewGroup parent)三个参数的意思
- MEMS微加工技术
- Sereja and Suffixes(思维)
- ListView判断滑动底部
- mac配置java环境
- PHP源码安装后设置别名
- .netcore入门
- check the manual that corresponds to your MySQL server version for the right syntax to use near &#39;desc
- CSS基础-DAY1
- Jboot使用appassembler-maven-plugin插件生成启动脚本
- css Table布局:基于display:table的CSS布局
- 【MFC】mfc控件位置调整和坐标确定 .
- Android学习笔记_16_添加多个Activity、参数传递、请求码和结果码使用