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

phptry {
  // Kod som kan orsaka ett undantag
} catch (Exception $e) {
  // Hantering av undantag
} finally {
  // Kod som alltid exekveras
}

Exempel

Exempel med lyckad kodexekvering:

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

Resultat av kodexekvering:

phpResult: 5
This will always execute

Exempel

Exempel med hantering av undantag:

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

Resultat av kodexekvering:

phpException: Division by zero
This will always execute

Exempel

Användning av finally för att frigöra resurser:

php<?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:

phpFile opened successfully
File closed in finally block

Se även

  • konstruktionen try,
    som används för att hantera undantag
  • klassen Exception,
    som är basklassen för alla undantag