Kommandot finally
Blocket finally används tillsammans med konstruktionerna try och catch för att hantera undantag. Koden inuti finally kommer alltid att exekveras - både vid lyckad exekvering av try-blocket och vid uppkomst av ett undantag.
Syntax
try {
// Kod som kan orsaka ett undantag
} catch (Exception $e) {
// Hantering av undantag
} finally {
// Kod som alltid exekveras
}
Exempel
Exempel med lyckad kodexekvering:
<?php
try {
$res = 10 / 2;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Resultat av kodexekvering:
Result: 5
This will always execute
Exempel
Exempel med hantering av undantag:
<?php
try {
$res = 10 / 0;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Resultat av kodexekvering:
Exception: Division by zero
This will always execute
Exempel
Användning av finally för att frigöra resurser:
<?php
$file = fopen("example.txt", "r");
try {
// Arbete med filen
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";
}
}
?>
Resultat av kodexekvering:
File opened successfully
File closed in finally block