Exception not catch by Try/Catch in PHP - 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.

Related

Can't catch exceptions in laravel

I have the following situation:
try {
DB::beginTransaction();
$task = new Task();
$task->setTracker("");
//thrown \Symfony\Component\Debug\Exception\FatalThrowableError
DB::commit();
}catch (\Exception $e){
DB::rollBack();
Log::error($e);
//throw $e;
}
I am not entering to the catch area.
Any idea why?
update
This is the error thrown:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to App\Models\Task::setTracker() must be an instance of Carbon\Carbon, integer given, called in /var/www/app/Services/ShareLogic.php on line 60
and will not be catched
Thanks
Catching Throwable did the trick.
Have no idea why?
Anyone does?
It does not catch the exception because you are trying to catch \Exception which Symfony\Component\Debug\Exception\FatalThrowableError does not extend.
Instead try to catch the actual exception by importing it..
use Symfony\Component\Debug\Exception\FatalThrowableError;
And then you can do..
try {
//
} catch(FatalThrowableError e) {
//
}
Edit
Ok, so in addition to the above solution it seems PHP 7+ handles error a bit differently than PHP 5. So try this..
try {
//
} catch(Error $e) {
// This should work
} catch(Throwable $e) {
// This should work as well
}
Symfony's Debug component is much more sophisticated in order to log and report all kinds of errors but take look at this simple example (php 7.1.x):
<?php
class MyUncatchableError extends Exception {}
function myExceptionHandler($e) {
throw new MyUncatchableError('BANG: '.$e->getMessage());
}
set_exception_handler('myExceptionHandler');
$foo = true;
try {
$foo->modify();
} catch (Exception $e) {
echo 'nope';
} catch (MyUncatchableError $e) {
echo 'nope2';
}
What will be the outcome? Well:
Fatal error: Uncaught MyUncatchableError: BANG: Call to a member function modify() on boolean in /in/WJErU:6
Stack trace:
0 [internal function]: myExceptionHandler(Object(Error))
1 {main}
thrown in /in/WJErU on line 6
and you can't catch that exception because you should catch the original.. throwable here, which is Error for this kind of "error". You can catch it by catching "Error" class. And with PHP7 hierarchy it implements Throwable interface, that's why you can't catch it using Exception (because while Exception implements Throwable, Error is no an Exception - see: http://php.net/manual/en/language.errors.php7.php).
And this is true for PHP7+ because with 5.* there was no Throwable nor Error, and doing $foo->modify(); would just stop the script and return a Fatal Error. You can make your own error handler (set_error_handler) and throw an exception there (and Debug component does that for php 5.*) but this method does not work for Fatal Errors. Instead Debug component hooks into script shutdown and reads last error and throws FatalErrorException.
This description may not be completely accurate as I have't dug deeply into Symfony but you can get the idea here.

Why this Exception can not be handled by catch try method

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.
}

Unable to catch an SQL exception

I have a Database class:
<?php
namespace Database\MySQL;
class Database
{
function __construct(){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$this->Connection = new mysqli(
"", // Testing with no host
"", // Testing with no user
"", // ... no password
"" // and no DB name
);
}
catch (mysqli_sql_exception $e) {
throw $e;
}
...
?>
But instead of a getting an exception, I get a Fatal error: Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'No database selected' in Database.php.
I have tried the same thing with a simple query:
try {
$this->Connection->query("SET NAMES 'utf87'"); //utf87 just for test
}
catch (mysqli_sql_exception $e) {
throw $e;
}
And I still get Fatal error: Uncaught exception.
Your problem is that you are catching the exception, but then just throwing it again without catching it.
If you replace throw $e; with echo "Caught the exception";, you will see that your script is catching the exception. But because you throw it again, it will result in an error unless you have a higher-level try/catch block or a global exception handler.
Also, as many have pointed out in the comments, you need to be careful of namespaces. You need to use a use statement or refer to \mysqli_sql_exception.

fatal error: Uncaught exception 'DOMPDF_Exception' with message 'Box property calculation requires containing block width'

When I try to process url http://www.bbc.co.uk/ dompdf throws error
fatal error: Uncaught exception 'DOMPDF_Exception' with message 'Box property calculation requires containing block width' in www\dompdf\include\block_frame_reflower.cls.php on line 171
It seems some settings or some bug?
DOMPDF_Exception is an extension of the Exception class. I'm not sure what parameters it will spit out, but you can dump the array out to see what is being returned:
try{
}catch(DOMPDF_Exception $e){
echo '<pre>',print_r($e),'</pre>';
}
Also found this on Google Code that might help you narrow down, what the actual issue is: http://code.google.com/p/dompdf/issues/detail?id=244
No, you just have to catch exceptions or set your stuff properly.
try {
//Do your stuff here
} catch (Exception $e){
echo $e->message() ;
}
I believe the correct way to return the message is
try {
//Do your stuff here
} catch (Exception $e){
echo $e->getMessage() ;
}

Exception handling in PHP: where does $e goes?

I been searching for this and I just seem to run into the same articles, in this code:
try
{
//some code
}
catch(Exception $e){
throw $e;
}
Where does $e gets stored or how the webmaster see it? Should I look for a special function?
An Exception object (in this case, $e) thrown from inside a catch{} block will be caught by the next highest try{} catch{} block.
Here's a silly example:
try {
try {
throw new Exception("This is thrown from the inner exception handler.");
}catch(Exception $e) {
throw $e;
}
}catch(Exception $e) {
die("I'm the outer exception handler (" . $e->getMessage() . ")<br />");
}
The output of the above is
I'm the outer exception handler (This is thrown from the inner exception handler.)
One nice thing is that Exception implements __toString() and outputs a call stack trace.
So sometimes in low-level Exceptions that I know I'm gonna want to see how I got to, in the catch() I simply do
error_log($e);
$e is an instance of Exception or any other class that extended from Exception. Those objects have some specific attributes and methods in common (inherited from the Exception class) you can use. See the chapter about exceptions and the Exception member list for more details.
I'm assuming your using some sort of third party code/library with this code in it that is throwing the exception into your code. You simply have to be ready for an exception to be thrown to catch it, then you can log it/display it however you want.
try {
$Library->procedure();
catch(Exception $e) {
echo $e->getMessage(); //would echo the exception message.
}
For more information read the PHP manual's entry on Exceptions.
The lines:
catch(Exception $e){
throw $e;
}
Don\t make sense. When you catch an Exception you're suppose to do something with the exception like:
catch(Exception $e){
error_log($e->getMessage());
die('An error has occurred');
}
But in your case the Exception is thrown directly to an outer try-block which would already happen.
If you change your code to:
//some code
Would create the exact same behaviour.

Categories