← Kembali ke kursus
Pelajaran kursus · Dart
Pelajaran 12

Exception handling

try/on/catch/finally, throw, Error vs Exception.

Pahami konsepnya

Dart punya try/catch/finally seperti biasa, plus on untuk tipe spesifik: try { } on FormatException catch (e) { } catch (e) { }. throw melempar; rethrow meneruskan.

Error vs Exception: Error untuk bug programmer (RangeError, TypeError) — tidak seharusnya ditangkap. Exception untuk kondisi runtime yang wajar (FormatException, IOException) — layak ditangani.

Coba contoh kode

int bagi(int a, int b) {
  if (b == 0) throw Exception("pembagi nol");
  return a ~/ b;
}

void main() {
  try {
    print(bagi(10, 2));
    print(bagi(10, 0));
  } on Exception catch (e) {
    print("Gagal: $e");
  } finally {
    print("Selesai.");
  }
}

on Exception catch (e) menangkap tipe spesifik. Interpolasi $e memanggil toString() untuk menampilkan detail exception; Exception umum tidak punya properti message. finally selalu berjalan.

Latihan singkat

Uji: throw Exception("test") → catch → cetak `test`.