I have written a very simple code to catch an exception in PHP but it still shows an error on the page . I am not able to understand why it does not catch the exception .
<?php
try
{
session_start();
echo ($counter);
}
catch(Exception $e)
{
echo "caught exception";
}
?>
Before php 7 you could only catch exceptions, not errors, but since php 7 you have a new interface called \Throwable that is more general than just exceptions and also the Error class was introduced that implements Throwable
http://php.net/manual/en/class.throwable.php
There are currently two types of Throwable objects, that is Exceptions and Errors,
So now you can also catch Errors,
However Fatal errors still break your code
you can try
<?php
try
{
session_start();
echo ($counter);
}
catch(\Exception $e)
{
echo "caught exception";
}
catch(\Error $e)
{
echo "caught error";
}
or you car try
try
{
session_start();
echo ($counter);
}
catch(\Throwable $e)
{
echo "caught exception";
}
Related
I found an really interesting problem on the internet about Exceptions & Errors, but I can't get it.
class MyException extends Exception {
public function __construct(string $message) {
$this -> message = $message;
}
}
class A {
public function __construct() {
throw new MyException("an error appeared");
}
}
$err = null;
try {
new A();
}
catch (MyException $err) {
throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
When I execute the code I receive
Fatal error: Uncaught Exception: another error appeared in C:\xampp
I don't understand if it's a problem about the code or this is how it works actually. Maybe you can help me.
That fatal error is for an untreated exception?
Thank you!
The second catch block does not catch the exception thrown in the first catch block. It can only be used to catch a an additional type of exception thrown in the first try block.
To catch your second exception you need to add a nested try catch:
try {
new A();
}
catch (MyException $err) {
try {
throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
}
Yes, the fatal error is for an unhandled exception here:
$err = null;
try {
new A();
}
catch (MyException $err) {
--->throw new Exception('another error appeared');
}
catch (Exception $err) {
echo $err;
}
In case you are wondering what is leading to this, it is this line in your code snippet:
$err = null;
try {
---> new A();
}
Exception
Exception 'Error' with message 'Class 'app\commands\CallLogs' not
found'
is not able to get caught in catch block.
Code:
I tried with calling undefined class just to see how and what exception catch block catches.
public function actionTest(){
try {
$logs = new CallLogs();
} catch (\yii\base\Exception $ex) {
print $ex->getMessage();
} catch(\ErrorException $ex){
print $ex->getMessage();
}
}
But, When I intentionally throw any exception, it works.
public function actionTest(){
try {
throw new \yii\base\Exception('hello');
} catch (\yii\base\Exception $ex) {
print $ex->getMessage();
} catch(\ErrorException $ex){
print $ex->getMessage();
}
}
I have tried with base\Exception class and \ErrorException class. But, no help.
Any help/hint is appreciable
catch (\Throwable $e) will do the job
\Throwable was introduced back in PHP 7.0 and is (quoting from docs) used for
[...] any object that can be thrown via a throw statement, including
Error and Exception.
Having read the article on this site here, I wrote this following code :
<?php
try{
annundefinedmethod();
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
?>
I wanted to show an error based on the proper exception for the function calling in the try block. However, all above exceptions didn't work, I still got an error saying uncaught error : call to undefined method.... what has gone wrong with my code?
You can't catch fatal errors in PHP. You may use 'is_callable' or 'function_exists' for this situation.
You may throw your own catch if you like:
try{
if (!is_callable('annundefinedmethod')) {
throw new BadFunctionCallException();
}
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
Quite simply an undefined method isn't the code throwing an exception.
try{
throw new Exception;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
You can also pass and call messages through in your exceptions and write them out in the catch block:
try{
throw new Exception('some useful error message');
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo $e->getMessage();
}
This is the same for the other type of exceptions you mention:
try{
throw new RuntimeException;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
And
try{
throw new BadFunctionCallException;
}
catch(RuntimeException $e){
echo 'Runtime exception called';
}
catch(BadFunctionCallException $e){
echo 'Bad function call exception called';
}
catch(Exception $e){
echo 'General exception called';
}
In PHP 5.x, you have to explicitly test if the function is callable first. You can't catch this type of error.
In PHP 7, errors such as this one are actually Error objects that implement Throwable. Error is a the new PHP 7 new base class for thrown internal PHP errors.
In this particular case, you are actually getting an Error object that implements Throwable. If you add a catch on either one of those types, you will be able to catch this error.
try {
annundefinedmethod();
}
catch (Error $e) {
//$e->getMessage() == "Call to undefined function annundefinedmethod()"
}
I am trying to pass an exception from a specific catch block to a more general catch block. However it does not appear to be working. I get a 500 server error when I try the following. Is this even possible?
I realize that there are easy workarounds, but isn't it normal to say, "Hey I don't feel like dealing with this error, let's have the more general exception handler take care of it!"
try {
//some soap stuff
}
catch (SoapFault $sf) {
throw new Exception('Soap Fault');
}
catch (Exception $e) {
echo $e->getMessage();
}
Technically this is what you're looking for:
try {
try {
//some soap stuff
}
catch (SoapFault $sf) {
throw new Exception('Soap Fault');
}
}
catch (Exception $e) {
echo $e->getMessage();
}
however I agree that exceptions shouldn't be used for flow control. A better way would be like this:
function show_error($message) {
echo "Error: $message\n";
}
try {
//some soap stuff
}
catch (SoapFault $sf) {
show_error('Soap Fault');
}
catch (Exception $e) {
show_error($e->getMessage());
}
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