简体   繁体   中英

Working of try / catch in ZF2

From the zend documentation i have learned that the try catch can be implemented. when i use zend exception,it cannot be caught even though the try is working

try { 
    loadClass() with a non-existant class will cause an exception 
    to be thrown in Zend_Loader: 
    Zend_Loader::loadClass('nonexistantclass'); 
} catch (Zend_Exception $e) { 
    echo "Caught exception"; 
    // Other code to recover from the error 
}

ERROR :Fatal error: Class 'Album\\Controller\\Zend\\Loader\\Loader' not found in C:\\wamp\\www\\zf\\module\\Album\\src\\Album\\Controller\\AlbumController.php on line 22 The catch is not happening error message is being shown

EDIT

But when i throw the exception as in the following code,i get the the message as error.

try { throw new \Exception("My exception"); } catch (Exception $e) { echo "Caught exception $e\n"; exit; }

There are a few issues here. Despite your code example, the error suggests you are using ZF2; and the error is a PHP fatal error, not an exception, which is why your try/catch doesn't work. There is no Zend_Loader in ZF2, so PHP won't be able to find that.

I'd suggest just using the standard PHP function class_exists() instead:

if (class_exists('Some\Class')) {
    ...
} else {
    ...
}

which should let you achieve what you're trying to do. No need to worry about exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM