Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: try-catch not catching all exceptions

I'm trying to do the following:

try {     // just an example     $time      = 'wrong datatype';     $timestamp = date("Y-m-d H:i:s", $time); } catch (Exception $e) {     return false; } // database activity here 

In short: I initialize some variables to be put in the database. If the initialization fails for whatever reason - e.g. because $time is not the expected format - I want the method to return false and not input wrong data into the database.

However, errors like this are not caught by the 'catch'-statement, but by the global error handler. And then the script continues.

Is there a way around this? I just thought it would be cleaner to do it like this instead of manually typechecking every variable, which seems ineffective considering that in 99% of all cases nothing bad happens.

like image 975
Marcos Avatar asked Mar 17 '13 14:03

Marcos


People also ask

Does exception catch all exceptions PHP?

Catching all PHP exceptions Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... }

Can PHP try have multiple catches?

PHP allows a series of catch blocks following a try block to handle different exception cases. Various catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions.


1 Answers

try {   // call a success/error/progress handler } catch (\Throwable $e) { // For PHP 7   // handle $e } catch (\Exception $e) { // For PHP 5   // handle $e } 
like image 172
Nabi K.A.Z. Avatar answered Oct 01 '22 12:10

Nabi K.A.Z.