Bifalgorithm post · Computer science one · Throwing Exceptions

How can you catch exceptions in PHP with try-catch-finally?

How can you catch exceptions in PHP with try-catch-finally? (Computer science one · Throwing Exceptions) — "To catch an exception in PHP you can use the standa…

Ideas in this flowchart

  • Gestion des exceptions et validation des entrées en PHP
  • Le bloc standard try-catch permet d'attraper une exception.
  • Depuis PHP 5.5.0, le bloc finally peut nettoyer des ressources ou exécuter du code, qu'une exception soit levée ou non.
  • La fonction readNumber illustre la lecture et l'analyse manuelle d'une entrée utilisateur.
  • La fonction demande à l'utilisateur d'entrer un nombre.
  • La valeur saisie est vérifiée pour déterminer si elle est numérique.
  • Si la valeur est numérique, elle est convertie en nombre flottant avec floatval.
  • Si la valeur n'est pas numérique, une exception « Invalid input! » est levée.
Feed/

How can you catch exceptions in PHP with try-catch-finally?

No cover

Channel

Computer science one

1 page

"To catch an exception in PHP you can use the standard try-catch control block. Optionally (and as of PHP version 5.5.0) you can use the finally block to clean up any resources or execute code regardless of whether or not an exception was raised. Consider the simple task of reading input from a user and manually parsing its value into an integer. If the user enters a non-numeric value, parsing will fail and we should instead throw an exception. Consider the following function.\n\n1 function readNumber() {\n\n2 $input = readline(\"Please enter a number: \");\n\n3 if( is_numeric($input) ) {\n\n4 $value = floatval($input);\n\n5 } else {\n\n6 throw new Exception(\"Invalid input!\");\n\n7 }\n\n8 }"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.