zoukankan      html  css  js  c++  java
  • Dart Learn Notes 04

    流程控制语句

    流程控制语句的作用就是控制代码的执行流程。

    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');
    }
  • 相关阅读:
    webpack devServer配置项的坑
    app混合开发 fastlick.js 在ios上 input标签点击 不灵敏 处理
    vue 学习八 自定义指令
    Verilog数值大小比较
    Verilog实现Matlab的fliplr函数
    基本不等式
    如何读取ila数据
    Xilinx FPGA时钟IP核注意事项
    FPGA Turbo译码器注意事项
    EbN0转SNR
  • 原文地址:https://www.cnblogs.com/restartyang/p/10594110.html
Copyright © 2011-2022 走看看