Throw exception and continue php

You can, but I will warn: many consider this method quite evil.

// https://stackoverflow.com/a/66377817/578023
function is_same(&$a, &$b): bool {
    $_ = [ &$a, &$b ];
    return
        \ReflectionReference::fromArrayElement($_, 0)->getId() ===
        \ReflectionReference::fromArrayElement($_, 1)->getId();
}

function attempt_risky_action($collection){
    $cursor=NULL;
    $resuming = false;
    
    resume:
    try{
        foreach($collection as $item){
            if($resuming && !is_same($cursor,$item) ){
                continue;                   // some things have better ways to skip ahead, especially an array index
            }
            else {
                $resuming = false;
                $cursor=&$item;             // main concept is to remember where you are in the iteration
            }                               // in some situation you may have to use references,  &item
            

            // your normal loop here
            .
            .
            .
        }
    }   catch( Exception $e){
        $resuming = repair_something($e, $collection);      // returns false if your repair ran out of ideas
        if($resuming)
            goto resume;
    }
    
    unset($cursor);
    
}

Ideally it would be best to wrap the unset($cursor); call in a finally{} block, but frankly I'm not sure how that plays with goto off hand.

If it executes because goto broke the flow then you will need some conditional logic, so the cursor still exists. If you have a return statement inside the loop you must use a finally block for call to unset($cursor) -- or cause a memory leak.

Then again, while less exciting, you can do this same trick by just nesting your whole loop in do{ try/catch } while($resuming). While that is not LITERALLY reversing your execution, it does exactly the same effect without risking a goto.

is_same() from https://stackoverflow.com/a/66377817/578023

function attempt_risky_action($collection){
    $cursor=NULL;
    $resuming = false;
    
    do{
        try{
            foreach($collection as $item){
                if($resuming && !is_same($cursor,$item) ){
                    continue;   
                }
                else {
                    $resuming = false;
                    $cursor=&$item;
                }

                // your loop here
            }
        }   catch( Exception $e){
            $resuming = repair_something($e, $collection);      // returns false if your repair ran out of ideas
        }
        finally{ 
            if(!$resuming){
                unset($cursor); 
            }
        }
    } while($resuming);
}

A last method, not pictured; you can use PHP's reset(), prev(), current(), next(), end() faculties

These will allow you instead to simply have your try/catch block inside a code block that iterates as a loop would -- then use prev() in the catch to try again.

Table of Contents

  • Extending Exceptions

PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

If an exception is thrown and its current function scope has no catch block, the exception will "bubble up" the call stack to the calling function until it finds a matching catch block. All finally blocks it encounters along the way will be executed. If the call stack is unwound all the way to the global scope without encountering a matching catch block, the program will terminate with a fatal error unless a global exception handler has been set.

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.

As of PHP 8.0.0, the throw keyword is an expression and may be used in any expression context. In prior versions it was a statement and was required to be on its own line.

catch

A catch block defines how to respond to a thrown exception. A catch block defines one or more types of exception or error it can handle, and optionally a variable to which to assign the exception. (The variable was required prior to PHP 8.0.0.) The first catch block a thrown exception or error encounters that matches the type of the thrown object will handle the object.

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block. If not, execution will continue after the catch block that was triggered.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

As of PHP 7.1.0, a catch block may specify multiple exceptions using the pipe (|) character. This is useful for when different exceptions from different class hierarchies are handled the same.

As of PHP 8.0.0, the variable name for a caught exception is optional. If not specified, the catch block will still execute but will not have access to the thrown object.

finally

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.

One notable interaction is between the finally block and a return statement. If a return statement is encountered inside either the try or the catch blocks, the finally block will still be executed. Moreover, the return statement is evaluated when encountered, but the result will be returned after the finally block is executed. Additionally, if the finally block also contains a return statement, the value from the finally block is returned.

Global exception handler

If an exception is allowed to bubble up to the global scope, it may be caught by a global exception handler if set. The set_exception_handler() function can set a function that will be called in place of a catch block if no other block is invoked. The effect is essentially the same as if the entire program were wrapped in a try-catch block with that function as the catch.

Notes

Note:

Internal PHP functions mainly use Error reporting, only modern Object-oriented extensions use exceptions. However, errors can be easily translated to exceptions with ErrorException. This technique only works with non-fatal errors, however.

Example #3 Converting error reporting to exceptions

function exceptions_error_handler($severity$message$filename$lineno) {
    throw new 
ErrorException($message0$severity$filename$lineno);
}
set_error_handler('exceptions_error_handler');
?>

Examples

Example #4 Throwing an Exception

function inverse($x) {
    if (!
$x) {
        throw new 
Exception('Division by zero.');
    }
    return 
1/$x;
}

try {
    echo

inverse(5) . "\n";
    echo 
inverse(0) . "\n";
} catch (
Exception $e) {
    echo 
'Caught exception: ',  $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #5 Exception handling with a finally block

function inverse($x) {
    if (!
$x) {
        throw new 
Exception('Division by zero.');
    }
    return 
1/$x;
}

try {
    echo

inverse(5) . "\n";
} catch (
Exception $e) {
    echo 
'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo 
"First finally.\n";
}

try {
    echo

inverse(0) . "\n";
} catch (
Exception $e) {
    echo 
'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo 
"Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #6 Interaction between the finally block and return

function test() {
    try {
        throw new 
Exception('foo');
    } catch (
Exception $e) {
        return 
'catch';
    } finally {
        return 
'finally';
    }
}

echo

test();
?>

The above example will output:

Example #7 Nested Exception

class MyException extends Exception { }

class

Test {
    public function 
testing() {
        try {
            try {
                throw new 
MyException('foo!');
            } catch (
MyException $e) {
                
// rethrow it
                
throw $e;
            }
        } catch (
Exception $e) {
            
var_dump($e->getMessage());
        }
    }
}
$foo = new Test;
$foo->testing();?>

The above example will output:

Example #8 Multi catch exception handling

class MyException extends Exception { }

class

MyOtherException extends Exception { }

class

Test {
    public function 
testing() {
        try {
            throw new 
MyException();
        } catch (
MyException MyOtherException $e) {
            
var_dump(get_class($e));
        }
    }
}
$foo = new Test;
$foo->testing();?>

The above example will output:

Example #9 Omitting the caught variable

Only permitted in PHP 8.0.0 and later.

class SpecificException extends Exception {}

function

test() {
    throw new 
SpecificException('Oopsie');
}

try {

test();
} catch (
SpecificException) {
    print 
"A SpecificException was thrown, but we don't care about the details.";
}
?>

Example #10 Throw as an expression

Only permitted in PHP 8.0.0 and later.

class SpecificException extends Exception {}

function

test() {
    
do_something_risky() or throw new Exception('It did not work');
}

try {

test();
} catch (
Exception $e) {
    print 
$e->getMessage();
}
?>

ask at nilpo dot com

13 years ago

If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

interface IException
{
   
/* Protected methods inherited from Exception class */
   
public function getMessage();                 // Exception message
   
public function getCode();                    // User-defined Exception code
   
public function getFile();                    // Source filename
   
public function getLine();                    // Source line
   
public function getTrace();                   // An array of the backtrace()
   
public function getTraceAsString();           // Formated string of trace

        /* Overrideable methods inherited from Exception class */

public function __toString();                 // formated string for display
   
public function __construct($message = null, $code = 0);
}

abstract class

CustomException extends Exception implements IException
{
    protected
$message = 'Unknown exception';     // Exception message
   
private   $string;                            // Unknown
   
protected $code    = 0;                       // User-defined exception code
   
protected $file;                              // Source filename of exception
   
protected $line;                              // Source line of exception
   
private   $trace;                             // Unknownpublic function __construct($message = null, $code = 0)
    {
        if (!
$message) {
            throw new
$this('Unknown '. get_class($this));
        }
       
parent::__construct($message, $code);
    }

        public function

__toString()
    {
        return
get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                               
. "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

function exceptionTest()
{
    try {
        throw new
TestException();
    }
    catch (
TestException $e) {
        echo
"Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (
Exception $e) {
        echo
"Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo

'
' . exceptionTest() . '
'
;
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}

Johan

11 years ago

Custom error handling on entire pages can avoid half rendered pages for the users:

ob_start();
try {
   
/*contains all page logic
    and throws error if needed*/
   
...
} catch (
Exception $e) {
 
ob_end_clean();
 
displayErrorPage($e->getMessage());
}
?>

christof+php[AT]insypro.com

5 years ago

In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

    set_error_handler(function($errno, $errstr, $errfile, $errline){
            if(
$errno === E_WARNING){
               
// make it more serious than a warning so it can be caught
               
trigger_error($errstr, E_ERROR);
                return
true;
            } else {
               
// fallback to default php error handler
               
return false;
            }
    });

    try {

// code that might result in a E_WARNING
   
} catch(Exception $e){
           
// code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
   
} finally {
           
restore_error_handler();
    }
?>

Shot (Piotr Szotkowski)

13 years ago

‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).

Edu

9 years ago

The "finally" block can change the exception that has been throw by the catch block.

try{
        try {
                throw new \
Exception("Hello");
        } catch(\
Exception $e) {
                echo
$e->getMessage()." catch in\n";
                throw
$e;
        } finally {
                echo
$e->getMessage()." finally \n";
                throw new \
Exception("Bye");
        }
} catch (\
Exception $e) {
        echo
$e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out

Simo

7 years ago

#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.

daviddlowe dot flimm at gmail dot com

4 years ago

Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

try {
    throw new
Error( "foobar" );
   
// or:
    // throw new Exception( "foobar" );
}
catch (
Throwable $e) {
   
var_export( $e );
}
?>

mlaopane at gmail dot com

4 years ago

/**
* You can catch exceptions thrown in a deep level function
*/
function employee()
{
    throw new \
Exception("I am just an employee !");
}

function

manager()
{
   
employee();
}

function

boss()
{
    try {
       
manager();
    } catch (\
Exception $e) {
        echo
$e->getMessage();
    }
}
boss(); // output: "I am just an employee !"

telefoontoestel at nospam dot org

8 years ago

When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

try {
    echo
"try block
"
;
    throw new
Exception("test");
} catch (
Exception $ex) {
    echo
"catch block
"
;
} finally {
    echo
"finally block
"
;
}
// try block
// catch block
// finally block
?>

try {
    echo
"try block
"
;
    throw new
Exception("test");
} catch (
Exception $ex) {
    echo
"catch block
"
;
    exit(
1);
} finally {
    echo
"finally block
"
;
}
// try block
// catch block
?>

Tom Polomsk

7 years ago

Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.

Sawsan

10 years ago

the following is an example of a re-thrown exception and the using of getPrevious function:

$name

= "Name";//check if the name contains only letters, and does not contain the word nametry
   {
   try
     {
      if (
preg_match('/[^a-z]/i', $name))
       {
           throw new
Exception("$name contains character other than a-z A-Z");
       }  
       if(
strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new
Exception("$name contains the word name");
       }
       echo
"The Name is valid";
     }
   catch(
Exception $e)
     {
     throw new
Exception("insert name again",0,$e);
     }
   }

catch (

Exception $e)
   {
   if (
$e->getPrevious())
   {
    echo
"The Previous Exception is: ".$e->getPrevious()->getMessage()."
"
;
   }
   echo
"The Exception is: ".$e->getMessage()."
"
;
   }
?>

Daan

1 year ago

I would like to emphasise that you can not rethrow an Exception inside a catch-block and expect that the next catch-block will handle it.

try {
    throw new
RuntimeException('error');           
} catch (
RuntimeException $e) {
    throw
$e;
} catch (
Exception $e) {
   
// this will not be executed[
}
?>

Does throwing an exception stop execution PHP?

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Does PHP have try catch?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

What is an exception how you can handle multiple exceptions in PHP?

Exception handling is a powerful mechanism of PHP, which is used to handle runtime errors (runtime errors are called exceptions). So that the normal flow of the application can be maintained. The main purpose of using exception handling is to maintain the normal execution of the application.

Does throw return PHP?

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.