Dart 語言簡易教程(五)

Dart 語言簡易教程(一): http://www.itdecent.cn/p/8a62b1a2fd75
Dart 語言簡易教程(二): http://www.itdecent.cn/p/b2153a32dd8b
Dart 語言簡易教程(三): http://www.itdecent.cn/p/6d2495a0d3d7
Dart 語言簡易教程(四): http://www.itdecent.cn/p/fdd046a6dc82

Dart 語言簡易教程(五)

流程控制語句

Dart 可用的流程控制語句:

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert
  • try-catch and throw

if and else

Dart 支持ifelse的多種組合。
和Python,Java,C++ 都有類似的操作。

例子:

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}

如前面的教程里面提到的那樣,Dart 中只有變量值為true 的時候才會返回true 的結(jié)果。

for 循環(huán)

for 循環(huán)的例子:

var message = new StringBuffer("Dart is fun");
for (var i = 0; i < 5; i++) {
  message.write('!');
}

除了常規(guī)的for 循環(huán)外,針對可以序列化的操作數(shù),可以使用forEach() 方法。
當(dāng)不關(guān)心操作數(shù)的當(dāng)前的下標(biāo)的時候,forEach()方法是很簡便的。
例子:

var collection = [0, 1, 2];
for (var x in collection) {
  print(x);
}

While and do-while

while 循環(huán)的例子:

main() {
  var _temp = 0;
  while(_temp < 5){

    print("this is loop: " + (_temp).toString());
    _temp ++;
  }
}

do-while 循環(huán)的例子:

main() {
  var _temp = 0;

  do{
    print("this is loop: " + (_temp).toString());
    _temp ++;
  }
  while(_temp < 5);
}

上面的兩個例子都對應(yīng)如下輸出:

this is loop: 0
this is loop: 1
this is loop: 2
this is loop: 3
this is loop: 4

Break 和 continue

break 用來跳出循環(huán)

while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}

continue 用來跳過本次循環(huán)

for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}

Switch 和 case

Dart 中switch / case 語句使用== 操作來比較整數(shù),字符串或其它編譯過程中的常量,從而實現(xiàn)分支的作用。
switch / case 語句的前后操作數(shù)必須是相同的類型的對象實例(即使其中一個操作數(shù)屬于另一個對象的子類的實例,比較操作也不行。)

每一個非空的case 子句(不是case 判斷語句本身,而是case 語句下面的實際操作。)最后都必須跟上break 語句。

var command = 'OPEN';
switch (command) {
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break causes an exception!!

  case 'CLOSED':
    executeClosed();
    break;
}
var command = 'CLOSED';
switch (command) {
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

使用switch / case 語句,配合 continue 語句。可以實現(xiàn)類似 goto 語句的功能。

var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    executeClosed();
    continue nowClosed;
    // Continues executing at the nowClosed label.

nowClosed:
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

斷言(assert)

Dart 語言通過使用assert 語句來中斷正常的執(zhí)行流程,中斷的前提是:assert 判斷的條件為 false 。

// Make sure the variable has a non-null value.
assert(text != null);

assert 判斷的條件可以是任何可以轉(zhuǎn)化為 boolean 類型的對象,即使是函數(shù)也可以(此時判斷的是函數(shù)返回值)。

如果assert 的判斷為true, 則繼續(xù)執(zhí)行下面的語句。反之則會丟出一個異 AssertionError 。

異常(Exceptions)

Dart 代碼可以丟出或捕獲異常。
異常表明發(fā)生了一些不預(yù)期的錯誤。
如果不捕獲異常,一旦異常發(fā)生,則程序和中斷執(zhí)行并停止運行。

Dart 代碼不會在代碼中指定代碼將會丟出什么異常,所以調(diào)用系統(tǒng)代碼時,不會強制要求處理異常。這點與Java 的處理方式是不同的。

Dart 提供 Exception 和 Error 類型來處理異常。自己也可以定義屬于自己的異常類型。

Throw

用于拋出異常。

throw new FormatException('Expected at least 1 section');

也可以通過throw 語句釋放任意的類型:

throw 'Out of llamas!';

因為拋出異常屬于表達式,可以將throw 語句放置在 =>語句中:

distanceTo(Point other) =>
    throw new UnimplementedError();

捕獲(Catch)

基本用法與Python 相同。
將可能出現(xiàn)異常的代碼放置到try 語句中,然后在氣候跟上 catch 語句來處理可能出現(xiàn)的異常。
可以通過 on語句來指定需要捕獲的異常類型,使用catch 來處理異常。

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  // A specific exception
  buyMoreLlamas();
} on Exception catch (e) {
  // Anything else that is an exception
  print('Unknown exception: $e');
} catch (e) {
  // No specified type, handles all
  print('Something really unknown: $e');
}

可以向catch()傳遞1個或2個參數(shù)。第一個參數(shù)表示:捕獲的異常的具體信息,第二個參數(shù)表示:異常的堆棧跟蹤(stack trace)。

  ...
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

rethrow語句用來處理一個異常,同時希望這個異常能夠被其它調(diào)用的部分使用。
如下的代碼:

final foo = '';

void misbehave() {
  try {
    foo = "You can't change a final variable's value.";
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}

void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}

Finally

Dart 的finally用來執(zhí)行那些無論異常是否發(fā)生都執(zhí)行的操作。

try {
  breedMoreLlamas();
} catch(e) {
  print('Error: $e');  // Handle the exception first.
} finally {
  cleanLlamaStalls();  // Then clean up.
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容