My code snippet is below - as you can see, I have a try-catch block, but inspite of this, I still get an uncaught exception that terminates the entire application. What am I missing?
try {
$cakeXml = simplexml_load_string($xml);
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
2014-12-16 22:45:12 Error: Fatal Error (1): Call to a member function xpath() on a non-object
2014-12-16 22:45:12 Error: [FatalErrorException] Call to a member function xpath() on a non-object
If you read the error message more-carefully, you will see that it is not dieing on an Exception, but on a Fatal Error. A try/catch statement cannot catch a fatal error in PHP, as there is no way to recover from a fatal error.
As for solving this issue, your error is telling you $cakeXml is a non-object. One solution would be to do something like this.
try {
$cakeXml = simplexml_load_string($xml);
if (!is_object($cakeXml)) {
throw new Exception('simplexml_load_string returned non-object');
}
$parseSuccess = $cakeXml->xpath('//ParseSuccess');
} catch (Exception $ex) {
$response['parseSuccess'] = false;
$response['errors']['ParseError'] = 'An unknown error occurred while trying to parse the file. Please try again';
return $response;
}
DOMXPath methods i.e. xpath or evaluate does not throw exceptions. Hence, you will need to explicitly validate and throw the exception.
See below code snippet:
$xml_1= "";
try {
$cakeXml = simplexml_load_string($xml_1);
if ( !is_object($cakeXml) ) {
throw new Exception(sprintf('Not an object (Object: %s)', var_export($cakeXml, true)));
} else {
$parseSuccess = $cakeXml->xpath('//pages');
print('<pre>');print_r($parseSuccess);
}
} catch (Exception $ex) {
echo 'Caught exception: ', $ex->getMessage(), "\n";
}
Related
When i initiate a class which does not exist , It throws the error, I Don't want to halted by that error . So i try trycatch method , But it still giving me same error, Can someone explain why this error is not been catched
I tried
try{$obj = new classname();}
catch(Exception $e){ echo 'class does not exist, move on' ;}
Fatal error: Class 'classname' not found in C:\WampDeveloper\Websites\localhost\webroot\index.php on line 4
Can someone explain why this error can not be catched ?
Is their is another way to catch and handle this kind of errors ?
UPDATE
We can catch mysql fatal errors by try catch method , So don't say fatal errors can not be handeled by try catch method
Two ways to solve this, use a autoloader that runs a custom written function for each object that does not exist so you can try to "include" a file on demand.
function autoload($objname){
if(is_readable(($f = '/path/to/class/'.$objname.'.php'))){
include $f;
} else {
throw Exception("$f does not exist");
}
}
spl_autoload_register('autoload');
new classname(); // try to load /path/to/class/classname.php
Or you can upgrade to PHP 7 where the error logic has had little overhaul:
Hierarchy
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
So a code like this would work:
try{
$obj = new classname();
} catch(Error $er){
echo 'class does not exist, move on';
} catch(Exception $ex){
echo 'a custom exception has been thrown:' . $ex->getMessage();
} catch(Throwable $t){
// Obsolete code, as Throwables are either Error or Exception, that were caught above.
}
Here is my code:
try {
if ( condition 1 ) {
throw;
} else {
// do something
}
// some code here
if ( condition 2 ){
throw;
}
} catch (Exception $e) {
echo "something is wrong";
}
As you see, my catch block has its own error message, And that message is a constant. So really I don't need to pass a message when I use throw like this:
throw new Exception('error message');
Well can I use throw without anything? I just need to jump into catch block.
Honestly writing an useless error message is annoying for me.
As you know my current code has a syntax error: (it referring to throw;)
Parse error: syntax error, unexpected ';' in {path}
message parameter is optional in the Exception constructor. So if you don't have/want to put - just don't:
throw new Exception;
But you still must throw an instance of the Exception class (or a class that extends it), since it is a part of the php language syntax.
If you want all your exceptions to have the same message, you can extend it and define the message in your class:
class AmbiguousException extends Exception {
public function __construct($message = 'Something is wrong.', $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
Then:
throw new AmbiguousException();
You can use the below throw everytime you need.
throw new Exception();
and catch will remain same as your code.
As stated in the PHP manual:
The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
You can throw an exception without any message:
throw new Exception();
Perhaps something to help you from duplicating the same exception is as follows:
$e = new Exception('something is wrong');
try {
throw $e;
} catch (Exception $ex) {
echo $ex->getMessage();
}
You can create an instance with default message and then throw that instance.
$Exception = new Exception("some error message!");
try {
throw $Exception;
} catch (Exception $ex) {
var_dump($ex);
}
You cannot use the throw keyword on its own. However, you can use throw new Exception(); without specify the $message parameter, because it'll just fallback to the default message. Check out the Exceptions section in the PHP manual: http://php.net/manual/en/language.exceptions.extending.php
i've try this example :
<?php
try {
Not_Exist();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
http://php.net/manual/en/language.exceptions.php
But the error is not catched :
Fatal error: Call to undefined function Not_Exist() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\mysite\public_html\exception.php on line 3
Why? I'm usually using Dotnet. Maybe i miss something.
error is not an exception. PHP itself doesn't throw exceptions on syntax errors, such as missing functions. You'd need set_error_handler() to "catch" such things - and even then, a custom error handler can't handle parse errors such as this.
There is no Exception being thrown in your code. You're simply hitting a fatal error. If you're trying to find a way around fatal errors, this post may be of help. How do I catch a PHP Fatal Error
If you're trying to catch Exceptions, something like this:
try {
throw new Exception("Exception Message");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Because that is a fatal error, not an exception. You're going to want to use PHP's function_exists() method and try something like:
try{
function_exists(Not_Exist);
} catch (Exception $e) {
// error here
}
// run Not_Exist here because we know its a valid function.
i am trying to connect to a webservice. My webserviceHelper is:
class webserviceHelper {
public function __construct($params) {
$this->service_url = $params['service_url'];
try {
$this->soap = new SoapClient($this->service_url,
array('exceptions' => true));
}
catch (SoapFault $exc) {
echo 'SoapFault<br />';
die;
}
catch (Exception $exc) {
echo 'Exception<br />';
die;
}
}
...
}
When the service is down, i make a request to the page where the webserviceHelper object created. Before the response i make second request to the same page. At first one, i got "soapFault" as output but at the second, i got a fatal error.
Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'WebService?wsdl' : failed to load external entity "WebService?wsdl" in webserviceHelper.php on line 40
How can i prevent this error?
use error_get_last() after $this->soap = new SoapClient(..... to get potential errors
I handled it by using a hook in codeigniter. Thanks to the blogger. How To Catch PHP Fatal Error In CodeIgniter
I got the following exception in my page:
Fatal error: Call to a member function someFunction() on a
non-object in seomfile.php on line 15
My code near line 15 is:
try
{
return getObject()->someFunction(); // line 15
}
catch(Exception $e) { }
I know getObject() returns null, but why isn't the try block catching it?
PHP mixes Exceptions and Errors. You could use set_error_handler() to throw an exception on error.
You can try to use something like this:
try {
$object = getObject();
If (!is_object($object)) {
throw new Exception();
}
return $object->someFunction();
catch (Exception $e) {
}
Because it's not an exception, it's a standard old-fashioned error.