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.
Related
I have the following PHP script, test.php in my Moodle plugin:
<?php
include('lib/httpful/httpful.phar');
try{
$response = \Httpful\Request::post($uri)
->body($requestbody)
->send();
}catch (Exception $e) {
echo "Exception occurred";
}
?>
Whenever an exception occurs the text "Exception Occurred" is displayed as expected.
Then I moved the code to a function in a class, classes\http_client.php. Thus:
class http_client{
public function doPost($uri, $requestbody){
try{
$response = \Httpful\Request::post($uri)
->body($requestbody)
->send();
}catch (Exception $e) {
echo "Exception occurred";
}
}
}
Now I try to invoke from test.php:
$client = new http_client();
$client->doPost($uri, $requestbody);
The exceptions are no longer caught and the stack trace is displayed in the browser.
I have to mention that it only happens within Moodle. Outside Moodle the class http_client works fine, the catch block is executed.
My settings are: Moodle 3.0.1+ (Build: 20151223), PHP 5.5.12, Apache 2.4.9.
Thanks in advance
I found the solution on this Moodle forum. https://moodle.org/mod/forum/discuss.php?d=207445. Since the class http_client was within a namespace (a fact I have stupidly omitted), I had to escape the Exception.
Thus:
}catch (\Exception $e) {
echo "Exception occurred";
}
\Exception $e instead of Exception $e.
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.
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";
}
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
I'd like to use an exception for error handling in a part of my code but if the code should fail, I would like the script to continue. I want to log the error though. Can someone please help me figure this out?
try{
if($id == 4)
{
echo'test';
}
}
catch(Exception $e){
echo $e->getMessage();
}
echo'Hello, you should see me...'; <------ I never see this.. No errors, just a trace.
You have to catch the exception :
// some code
try {
// some code, that might throw an exception
// Note that, when the exception is thrown, the code that's after what
// threw it, until the end of this "try" block, will not be executed
} catch (Exception $e) {
// deal with the exception
// code that will be executed only when an exception is thrown
echo $e->getMessage(); // for instance
}
// some code, that will always be executed
And here are a couple of things you should read :
Exceptions in the PHP manual
Exceptional PHP: Introduction to Exceptions
In the code that is calling the code that may throw an Exception do
try {
// code that may break/throw an exception
echo 'Foo';
throw new Exception('Nothing in this try block beyond this line');
echo 'I am never executed';
throw new CustomException('Neither am I');
} catch(CustomException $e) {
// continue here when any CustomException in try block occurs
echo $e->getMessage();
} catch(Exception $e) {
// continue here when any other Exception in try block occurs
echo $e->getMessage();
}
// script continues here
echo 'done';
Output will be (adding line breaks for readability):
'Foo' // echoed in try block
'Nothing in this try block beyond this line' // echoed in Exception catch block
'done' // echoed after try/catch block
Try/Catch Blocks may also be nested. See Example 2 in the PHP Manual page linked above:
try{
try {
throw new Exception('Foo');
echo 'not getting here';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'bar';
} catch (Exception $e) {
echo $e->getMessage();
}
echo 'done';
'Foo' // echoed in inner catch block
'bar' // echoed after inner try/catch block
'done' // echoed after outer try/catch block
Further reading at DevZone:
http://devzone.zend.com/node/view/id/666
http://devzone.zend.com/article/679-Exceptional-Code---PART-2
http://devzone.zend.com/node/view/id/652
http://devzone.zend.com/article/653-PHP-101-PART-12-BUGGING-OUT---PART-2