Komanda finally

Blloku finally përdoret së bashku me konstruktet try dhe catch për trajtimin e përjashtimeve. Kodi brenda finally do të ekzekutohet në çdo rast - si në ekzekutimin e suksesshëm të bllokut try, ashtu edhe në rastin e ndodhjes së një përjashtimi.

Sintaksa

phptry {
  // Kodi që mund të shkaktojë përjashtim
} catch (Exception $e) {
  // Trajtimi i përjashtimit
} finally {
  // Kodi që do të ekzekutohet në çdo rast
}

Shembull

Shembull me ekzekutim të suksesshëm të kodit:

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

Rezultati i ekzekutimit të kodit:

phpResult: 5
This will always execute

Shembull

Shembull me trajtim të përjashtimit:

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

Rezultati i ekzekutimit të kodit:

phpException: Division by zero
This will always execute

Shembull

Përdorimi i finally për çlirimin e burimeve:

php<?php
$file = fopen("example.txt", "r");
try {
  // Punë me skedarin
  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";
  }
}
?>

Rezultati i ekzekutimit të kodit:

phpFile opened successfully
File closed in finally block

Shihni gjithashtu

  • konstruktin try,
    që përdoret për trajtimin e përjashtimeve
  • klasën Exception,
    që është klasa bazë për të gjitha përjashtimet