364 of 410 menu

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

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
Shqip
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEnglishEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
Ne përdorim cookie për funksionimin e sajtit, analizën dhe personalizimin. Përpunimi i të dhënave bëhet në përputhje me Politikën e Privatësisë.
prano të gjitha konfiguro refuzo