unhandled errors in php - php

How can I know during runtime that my code threw a Warning?
example
try {
echo (25/0);
} catch (exception $exc) {
echo "exception catched";
}
throws a "Warning: Division by zero" error that i can not handle on my code.

You're looking for the function set_error_handler(). Check out the sample code in the manual.
Make sure that you don't only suppress the error warnings, but instead silently redirect them to a log file or something similar. (This helps you track down bugs)

You need to handle the exception yourself as follows.e.g
function inverse($x)
{
if(!$x)
{
throw new Exception('Division by zero.');
}
else
{
return 1/$x;
}
}
try
{
echo inverse(5);
echo inverse(0);
}
catch (Exception $e)
{
echo $e->getMessage();
}

You need to install an error handler that converts old style php "errors" into exceptions. See an example here

Related

Respect Validation and reset connection

I'm using the Respect\Validation library and I cannot get meaningful exceptions to print out apart from the first message.
This code gives me an error:
try {
$foo = \Respect\Validation\Validator::notEmpty();
$foo->assert('');
} catch (\InvalidArgumentException $e) {
echo $e->getFullMessage();
}
Error code: ERR_CONNECTION_RESET
However, this code works fine:
try {
$foo = \Respect\Validation\Validator::notEmpty();
$foo->check('');
} catch (\InvalidArgumentException $e) {
echo $e->getMainMessage();
}
I've tried turning off Xdebug but that didn't solve the problem. My version of PHP is 5.4.3.

Get all the exceptions from one try catch block

I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}

What's the `finally` keyword for in PHP?

Consider these two examples
<?php
function throw_exception() {
// Arbitrary code here
throw new Exception('Hello, Joe!');
}
function some_code() {
// Arbitrary code here
}
try {
throw_exception();
} catch (Exception $e) {
echo $e->getMessage();
}
some_code();
// More arbitrary code
?>
and
<?php
function throw_exception() {
// Arbitrary code here
throw new Exception('Hello, Joe!');
}
function some_code() {
// Arbitrary code here
}
try {
throw_exception();
} catch (Exception $e) {
echo $e->getMessage();
} finally {
some_code();
}
// More arbitrary code
?>
What's the difference? Is there a situation where the first example wouldn't execute some_code(), but the second would? Am I missing the point entirely?
If you catch Exception (any exception) the two code samples are equivalent. But if you only handle some specific exception type in your class block and another kind of exception occurs, then some_code(); will only be executed if you have a finally block.
try {
throw_exception();
} catch (ExceptionTypeA $e) {
echo $e->getMessage();
}
some_code(); // Will not execute if throw_exception throws an ExceptionTypeB
but:
try {
throw_exception();
} catch (ExceptionTypeA $e) {
echo $e->getMessage();
} finally {
some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}
fianlly block is used when you want a piece of code to execute regardless of whether an exception occurred or not...
Check out Example 2 on this page :
PHP manual
Finally will trigger even if no exception were caught.
Try this code to see why:
<?php
class Exep1 extends Exception {}
class Exep2 extends Exception {}
try {
echo 'try ';
throw new Exep1();
} catch ( Exep2 $e)
{
echo ' catch ';
} finally {
echo ' finally ';
}
echo 'aftermath';
?>
the output will be
try finally
Fatal error: Uncaught exception 'Exep1' in /tmp/execpad-70360fffa35e/source-70360fffa35e:7
Stack trace:
#0 {main}
thrown in /tmp/execpad-70360fffa35e/source-70360fffa35e on line 7
here is fiddle for you. https://eval.in/933947
From the PHP manual:
In PHP 5.5 and later, a finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
See this example in the manual, to see how it works.
http://www.youtube.com/watch?v=EWj60p8esD0
Watch from: 12:30 onwards
Watch this video.
The language is JAVA though.
But i think it illustrates Exceptions and the use of finally keyword very well.

Cleanest way to execute code outside of try block only if no exception is thrown

This question is about the best way to execute code outside of try block only if no exception is thrown.
try {
//experiment
//can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
//contain the blast
} finally {
//cleanup
//this is not the answer since it executes even if an exception occured
//finally will be available in php 5.5
} else {
//code to be executed only if no exception was thrown
//but no try ... else block exists in php
}
This is method suggested by #webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
So what is a better (or the best) way to accomplish this without the need for an extra variable?
One possibility is to put the try block in a method, and return false if an exception is cought.
function myFunction() {
try {
// Code that throws an exception
} catch(Exception $e) {
return false;
}
return true;
}
Have your catch block exit the function or (re)throw/throw an exception. You can filter your exceptions as well. So if your other code also throws an exception you can catch that and (re)throw it. Remember that:
Execution continues if no exception is caught.
If an exception happens and is caught and not (re)throw or a new one throw.
You don't exit your function from the catch block.
It's always a good idea to (re)throw any exception that you don't handle.
We should always be explicit in our exception handling. Meaning if you catch exceptions check the error that we can handle anything else should be (re)throw(n)
The way I would handle your situation would be to (re)throw the exception from the second statement.
try {
$this->throwExceptionA();
$this->throwExceptionB();
} catch (Exception $e) {
if($e->getMessage() == "ExceptionA Message") {
//Do handle code
} elseif($e->getMessage() == "ExceptionB Message") {
//Do other clean-up
throw $e;
} else {
//We should always do this or we will create bugs that elude us because
//we are catching exception that we are not handling
throw $e;
}
}

What is the PHP equivalent to Python's Try: ... Except:

I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.
This is what it would look like in Python:
try:
print "stuf"
except:
print "something else"
What would this be in PHP?
http://php.net/manual/en/language.exceptions.php
try {
print 'stuff';
} catch (Exception $e) {
var_dump($e);
}
Note: this only works for exceptions, not errors.
See http://www.php.net/manual/en/function.set-error-handler.php for that.
try {
// do stuff ...
} catch (Exception $e) {
print($e->getMessage());
}
See http://php.net/manual/en/language.exceptions.php
PHP does not natively support error catching like Python does, unless you override the default behavior and set your own error handler. PHP's try - catch was only recently added to the language in version 5, and it can only catch exceptions you explicitly throw.
So basically, PHP distinguishes between errors and exceptions. Errors haven't been modularized and made available to the user like they have been in Python. I believe that's related to the fact that PHP began as a collection of dynamic web scripts, grew and gained more features over time, and only more recently offered improved OOP support (i.e., version 5); whereas Python fundamentally supports OOP and other meta-functionality. And exception handling from the beginning.
Here's an example usage (again, a throw is necessary, or else nothing will be caught):
function oops($a)
{
if (!$a) {
throw new Exception('empty variable');
}
return "oops, $a";
}
try {
print oops($b);
} catch (Exception $e) {
print "Error occurred: " . $e->getMessage();
}
You can handle PHP errors like they were exceptions by using set_error_handler
In this error handler function you can throw various exception, according to error level for instance.
By doing this you can treat any error (including programming errors) in a common way.
PHP 5 has the exception model:
try {
print 'stuff';
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Assuming you're trying to catch exceptions, take a look at http://php.net/manual/en/language.exceptions.php
You could try something like
try {
echo "Stuff";
} catch (Exception $e) {
echo "Something Else";
}

Categories