Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception instead of error from a PHP extension [closed]

Another co-worker and I have been heavily modifying the PHP Zookeeper extension but the one thing really bothering me is the reliance on PHP error's vs Exceptions.

The original source is here: http://github.com/andreiz/php-zookeeper/blob/master/php_zookeeper.c#L209

Instead it would be nicer to throw up a Zookeeper_NodeNotExists or similar except I have no idea what the API call in c is.

I've tried googling and got a cornucopia result set of Exceptions in the PHP language, the PHP manual doesn't seem to mention them, and I can't remember which PHP stock extensions throw exception for you. Is there an alternative source of documentation on the PHP/Zend c API out there?

like image 736
David Avatar asked Oct 14 '10 20:10

David


People also ask

Does throwing an exception stop execution PHP?

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

What is throw exception PHP?

The throw keyword is used to throw exceptions. Exceptions are a way to change the program flow if an unexpected situation arises, such as invalid data.

What is the difference between error and exception in PHP?

Summary of Differences: An error message with filename, line number and a message describing the error is sent to the browser. Exceptions are used to change the normal flow of a script if a specified error occurs. This can be done using PHP die() Function.

How is exception handled in PHP also how do you explain how error reporting is done in PHP?

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors (runtime errors are called exceptions). So that the normal flow of the application can be maintained. The main purpose of using exception handling is to maintain the normal execution of the application.


1 Answers

I looked at the source code for PHP 5.3's Sqlite extension, specifically Sqlite.c which I knew threw an exception and found

via sqlite - https://github.com/php/php-src/blob/PHP-5.3/ext/sqlite/sqlite.c#L46

#include "zend_exceptions.h"

In zend_exceptions.h, it looks like a RuntimeException can be raised via a simple call to

zend_throw_exception(NULL, "Some text")

as explained here https://github.com/php/php-src/blob/PHP-5.3/Zend/zend_exceptions.h#L43

The Sqlite3 extension uses it like so:

zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Already initialised DB Object", 0 TSRMLS_CC);

where I infer that zend_exception_get_default() gets a reference/handle to RuntimeException, the 2nd argument is the Exception message, and all other work is delegated.

like image 90
David Avatar answered Oct 25 '22 02:10

David