Finally komandasi

finally bloku istisnaları emal etmək üçün try və catch konstruksiyaları ilə birlikdə istifadə olunur. Finally-in içərisindəki kod hər halda - həm try-blokunun uğurlu icrasında, həm də istisna yarananda icra olunacaq.

Sintaksis

phptry {
  // Istisna yarada biləcək kod
} catch (Exception $e) {
  // Istisnanın emalı
} finally {
  // Hər halda icra olunacaq kod
}

Nümunə

Kodun uğurlu icrası ilə nümunə:

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";
}
?>

Kodun icra nəticəsi:

phpResult: 5
This will always execute

Nümunə

Istisnanın emalı ilə nümunə:

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";
}
?>

Kodun icra nəticəsi:

phpException: Division by zero
This will always execute

Nümunə

Resursları azad etmək üçün finally-dən istifadə:

php<?php
$file = fopen("example.txt", "r");
try {
  // Fayl ilə iş
  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";
  }
}
?>

Kodun icra nəticəsi:

phpFile opened successfully
File closed in finally block

Həmçinin baxın

  • try konstruksiyası,
    istisnaları emal etmək üçün istifadə olunur
  • Exception sinifi,
    bütün istisnalar üçün əsas sinifdir