Bifalgorithm post · Computer science one · Catching Exceptions

How do you catch exceptions in PHP?

How do you catch exceptions in PHP? (Computer science one · Catching Exceptions) — "To catch an exception in PHP you can use the standard try-catch control blo…

Ideas in this flowchart

  • Exception handling in PHP
  • The standard try-catch control block catches exceptions.
  • The optional finally block is available as of PHP 5.5.0.
  • finally cleans up resources or executes code regardless of whether an exception was raised.
  • The readNumber() example reads user input and parses it into a number.
  • The function prompts the user to enter a number.
  • Is the entered value numeric?
  • If the value is numeric, floatval() converts it into a number.
  • If the value is not numeric, the function throws an exception with the message "Invalid input!".
Feed/

How do you catch exceptions in PHP?

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.