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
try {
// 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
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:
Result: 5
This will always execute
Nümunə
Istisnanın emalı ilə nümunə:
<?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:
Exception: Division by zero
This will always execute
Nümunə
Resursları azad etmək üçün finally-dən istifadə:
<?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:
File opened successfully
File closed in finally block