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
try {
// 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
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:
Result: 5
This will always execute
Shembull
Shembull me trajtim të përjashtimit:
<?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:
Exception: Division by zero
This will always execute
Shembull
Përdorimi i finally për çlirimin e burimeve:
<?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:
File opened successfully
File closed in finally block