I'm not very smooth with PHP, because I'm only using it temporary. The nature of my code is very simple, and it does have a few cases where it comes to a "uncaught exception: exit".
How exactly can I use the exception handler to tell it restart the code when it gets this error?
See: http://php.net/manual/en/language.exceptions.php
Use try-catch statement:
try {
//your code here
} catch (Exception e) {
// do something if an exception is thrown.
}
Related
Here's a simple event loop with a ReactPHP promise:
new React\Http\Server([
function(ServerRequestInterface $request) {
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();
$deferred->reject(new Response(500));
return $promise;
}
]);
In this case everything works fine and the server returns 500, because the promise was returned and it was rejected.
But how to handle cases like this:
new React\Http\Server([
function(ServerRequestInterface $request) {
$deferred = new React\Promise\Deferred();
$promise = $deferred->promise();
SynTaxErrO..2!((r();
$deferred->reject(new Response(500));
return $promise;
}
]);
The server/loop will still be running, but the connection will be hanging, since a syntax error happened before the promise was returned.
My first assumption was to use try-catch, but it doesn't seem to work in PHP.
try {
SynTaxErrO..2!((r();
} catch($e) {
$deferred->reject(new Response(500));
return $promise;
}
Is there a way to deal with cases like this and still return 500 instead of just hanging and waiting for a promise that was never returned? In real code I have a router function that returns a promise. The promise is never retuned if one of the routes have a syntax error, and thus the connection just hangs. There are no error messages as well.
You cannot catch syntax errors. If there is a syntax error before your catch statement, then execution never reaches your catch and therefore is like it didn't exist. To detect syntax error use a linter (for instance, php -l) before executing your code.
For other kinds of errors, provided you are using PHP 7, then you can use
catch (Error $e) { ... }
or a set_exception_handler() handler to catch errors.
If you want to catch both errors and exceptions, then you can use a block like
catch (Throwable $e) { ... }
If you only want to catch exceptions, use
catch (Exception $e) { ... }
See http://php.net/manual/en/language.errors.php7.php for more info
Hey ReactPHP team member here. Looks like the culput of you issue is SynTaxErrO..2!((r();, PHP can't parse that: https://3v4l.org/02cli
The best solution is not to have any syntax errors. A package that you could use to lint all your files before committing/deploying is: https://github.com/JakubOnderka/PHP-Parallel-Lint
I'm studying PHP right now and I'm using w3schools, but when I use the code below my page gets broken (stops from where the code is):
<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
This code is for creating an exception when no catch block was found.
I tried the others examples in the page and everything works fine. I thought it may be happening because there is no try block, but I'm confused and I don't know how to use it in this situation.
Thanks in advance!
set_exception_handler documentation from php.net:
http://php.net/manual/en/function.set-exception-handler.php
Execution will stop after the exception_handler is called.
Actually the output you are getting is correct.
As stated in W3Schools documentation set_exception_handler() only sets a user-defined function to handle all uncaught exceptions (as in the example you quoted above). So the output should be something like this:
Exception: Uncaught Exception occurred
Please notice the form of exception is what you have defined in your function (myException); which means first it prints the word Exception: and then it prints the reason (message) of exception, in this case Uncaught Exception occurred.
EDIT
As mentioned in the comments the error handler causes the script to stop being executed. To avoid this situation is better always to handle exceptions using try catch blocks.
P.S: I'd suggest you to use better resources other than W3Schools (like the PHP documentations itself) if you are starting to learn PHP.
try this. Hope it helps. If not please let me know.
function myException($exception) {
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e->getMessage();
}
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
I suppose that the exception system of PHP will catch all. but it doesn't.
try{
$obj = new Asdfasdfasdf()
} catch(Exception $e){
trace(...something...)
}
But it doesn't catch this kind of error, and I have searched php document, which didn't say which kind of exception/error is catch-able in try,catch clause.
So, how can I know that which kind of exception/error will be catched by my catch clause ?
P.S.
I finnally understand the 'error' from php engine is not the 'exception' from use land code. If you want use exception to handle engine 'error', you should manually wrap all 'error' in exception.
If you want to throw an Exception in the event that a class does not exist it, you could use class_exists().
A naive example might look something like:
function createClass($class)
{
if (!class_exists($class)) {
throw new Exception(
sprintf('Class %s does not exist', $class)
);
}
return new $class;
}
try {
$asdfasdfasdf = createClass('Asdfasdfasdf');
} catch (Exception $e) {
echo $e->getMessage();
}
From my experience, most PHP frameworks throw some sort of exception when a class is not found - for example, Symfony2 throws a ClassNotFoundException. That said, I don't know if you can 'catch' that, it's probably really just a development aid.
PHP 7 has just been released and from what I understand from the spec, you will be able to catch a fatal error as an EngineException. I don't know if it would work for your example; I haven't tested it because I have not installed PHP 7 stable yet. I tried your example with an alpha release of PHP 7 on an online REPL, and it appears that it does not work.
However for completeness, here's an example from the RFC:
function call_method($obj) {
$obj->method();
}
try {
call_method(null); // oops!
} catch (EngineException $e) {
echo "Exception: {$e->getMessage()}\n";
}
// Exception: Call to a member function method() on a non-object
In any case, as noted by #MarkBaker and #MarcB in the question's comments, you cannot "catch" a fatal error in previous versions of PHP.
Hope this helps :)
This probably sounds ridiculous. However, if you don't ask you'll never learn.
I'm relatively new to PHP and self-taught so I haven't exactly learnt everything "to the book".
Is the following required:
try {
}
catch {
}
Am I right in thinking that the try will try to "execute" the code within the brackets and the catch will try and catch the result of the outcome? If there is nothing to catch then it will throw an error?
The first assumption is correct: the code in try will be attempted to run.
However, if no error is thrown, then the block exits normally. If there is an error thrown, then the try execution ends early and goes into the catch block. So your second idea is switched.
try catch is used for exception handling or error handling.Put your script in try block and write your custom error message in catch block.
try{
// put here script
}catch(Exception $error){
//your custom message
echo 'Caught exception: ', $error->getMessage(), "\n";
}
If your script does not execute then it will be jump catch block and access message using $error object.
What is the benefit? The benefit is the whole script will not be stop to execute. It will be continue other block.
In the try block you execute code, whenever something fails in that block it will jump to the catch block. You usually define a variable holding the exception.
So to answer your question, no it will not process the catch block when there is nothing going wrong in the try block. (unless you specifically throw an exception)
try {
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Try block is hold the code which you want to execute. and Catch block is hold the code if you have cause any error then it will execute the catch code or error message.
Basically try and catch we are using for the error handling and avoid to break the control flow of the program and page.
Simple example:
<?php
class A {
public function getA($a = 0)
{
if ($a === 0) {
throw new ItCantBeZeroException("Message");
}
return $a;
}
}
// I want to throw default exception because I'm not sure
// am I doing it right or what can I do with bad parameter.
$a = new A;
echo $a->getA(0);
// Now, I know what I can do if developer write bad input.
// It can't be 0, so I just print my custom error message
// to my page.
try {
$a = new A;
echo $a->getA(0);
} catch (ItCantBeZeroException $e) {
echo "Parameter can't be zero. Try again.";
}
?>
You can define your own exceptions (like ItCantBeZeroException). Exceptions throw error on site (like "Message") but we can catch them and change to something we want.
You write simple class where some code must be string or integer between 0 and 20.
You use this code, but when user make variable 21, simple class throw error.
You refactor code to catch exception and try to fix code, e.g. change any integer greater than 20 to 20. Then code works properly.
Try and Catch is known as Exception Handling
According to w3schools:
Exceptions Handling are used to change the normal flow of a script if a specified error occurs.
For More:
http://www.w3schools.com/php/php_exception.asp
catch is not working because there is installed an exception handler using set_exception_handler()
I need "catch" to work, so I guess I need to unset the exception handler somehow. Things such as set_exception_handler(NULL) isn't working.
Any ideas how to unset the exception handler?
function my_exception_handler($exception) {
error_log("caught exception: " . $exception->getMessage() );
}
set_exception_handler("my_exception_handler");
// QUESTION: how does on unset it ?
//set_exception_handler(NULL);
try {
throw new Exception('hello world');
error_log("should not happen");
} catch(Exception $e) {
error_log("should happen: " . $e->getMessage());
}
Actual output:
caught exception: hello world
Desired output:
should happen: hello world
restore_exception_handler, which is linked from the manual entry for set_exception_handler.
BTW, these exception handlers should only come into play when an exception is uncaught. A catch block should always have precedence.
Reading a little bit in the comments on the Exceptions page brings you to this bug and this bug. They describe exactly what you experience, Exceptions can't be caught when a custom error handler is defined.
Solution:
Fixed in 5.3 and HEAD, won't be backported to 5.2.
The function is restore_exception_handler. However, the handler should only be called when an exception is unhandled. It does not disable catches.