Exceptions
throw carries an object; catch catches a specific type.
throw new RuntimeException('bad') interrupts the function. try goes around the narrow spot, and catch (RuntimeException $ex) catches that type. Catching a bare Exception to swallow everything is a way to hide a defect until production.
finally runs after success and after an exception alike. That is where you close a resource, not where you make a business decision. The practice function has no resource: returning the string bad or a number is enough.
An exception does not replace an ordinary if for an expected fork. "The user does not exist" is often better as an empty result or a 404. "The string had to be a number, and it is too late to handle that here" is an exception. At the boundary it is turned into a response.
Do not print $ex->getTraceAsString() to the client. It contains paths and pieces of data. In the task, only bad or the parsed number goes out. The log and the client response are different texts.
Practice
What to catch
Which catch is more honest at a narrow spot?
- catch (Exception $ex) around the whole file
- catching a specific type
- always a catch without a variable and with an empty body
- no try at all; let the client get a stack trace
What must not go out
Is an exception stack trace a good response text for the client? Answer yes or no.
A number or bad
Write function parse_num($s). If the string is an integer, including a negative one, return it as a decimal string. Otherwise return bad.