Perintah finally

Blok finally digunakan bersama dengan konstruksi try dan catch untuk menangani pengecualian. Kode di dalam finally akan dieksekusi dalam keadaan apa pun - baik saat blok try berhasil dieksekusi maupun saat pengecualian terjadi.

Sintaks

phptry {
  // Kode yang mungkin memicu pengecualian
} catch (Exception $e) {
  // Penanganan pengecualian
} finally {
  // Kode yang akan dieksekusi dalam keadaan apa pun
}

Contoh

Contoh dengan eksekusi kode yang berhasil:

php<?php
try {
  $res = 10 / 2;
  echo "Result: " . $res . "\n";
} catch (Exception $e) {
  echo "Exception: " . $e->getMessage() . "\n";
} finally {
  echo "This will always execute\n";
}
?>

Hasil eksekusi kode:

phpResult: 5
This will always execute

Contoh

Contoh dengan penanganan pengecualian:

php<?php
try {
  $res = 10 / 0;
  echo "Result: " . $res . "\n";
} catch (Exception $e) {
  echo "Exception: " . $e->getMessage() . "\n";
} finally {
  echo "This will always execute\n";
}
?>

Hasil eksekusi kode:

phpException: Division by zero
This will always execute

Contoh

Penggunaan finally untuk membebaskan sumber daya:

php<?php
$file = fopen("example.txt", "r");
try {
  // Bekerja dengan file
  if ($file) {
    echo "File opened successfully\n";
  }
} catch (Exception $e) {
  echo "Exception: " . $e->getMessage() . "\n";
} finally {
  if ($file) {
    fclose($file);
    echo "File closed in finally block\n";
  }
}
?>

Hasil eksekusi kode:

phpFile opened successfully
File closed in finally block

Lihat juga

  • konstruksi try,
    yang digunakan untuk menangani pengecualian
  • kelas Exception,
    yang merupakan kelas dasar untuk semua pengecualian