Does throwing exception break loop php?

Is it less efficient to put a try-catch block inside of a loop as opposed to wrapping the loop with a try-catch in php if it is intended that the loop will end if an exception occurs? Or is there essentially no difference?

EDIT:

i.e.,

foreach [/*...*/] {
    //...
    try {
        //...
    } catch [/*...*/] {
        break;
    }
    //...
}

versus:

try {
    foreach [/*...*/] {
        //...
    }
}

asked Jan 12, 2011 at 20:07

2

That entirely depends on the nature of the failure, and what you intend to do in the catch.

But I'd generalize it like so

  • If you want the loop to exit on Exception, wrap the whole loop
  • If you want the loop to continue, don't

EDIT

Exceptions caught inside a loop don't implicitly break the loop

for [$i = 1; $i < 10; $i++] {
    try {
        if [$i % 3 == 0] {
            throw new Exception['BOOM'];
        }
        echo $i;
    } catch [Exception $e] {
        echo "Exception at $i";
    }
    echo PHP_EOL;
}

output:

1
2
Exception at 3
4
5
Exception at 6
7
8
Exception at 9

Whereas those caught outside the loop do

try {
    for [$i = 1; $i < 10; $i++] {
        if [$i % 3 == 0] {
            throw new Exception['BOOM'];
        }
        echo $i, PHP_EOL;
    }
} catch [ Exception $e ] {
    echo "Exception at $i";
}

output:

1
2
Exception at 3

answered Jan 12, 2011 at 20:10

Peter BaileyPeter Bailey

104k31 gold badges180 silver badges201 bronze badges

6

That depends entirely on how you are using the try-catch? Is it safe to continue looping through your subject if an exception was thrown?

answered Jan 12, 2011 at 20:09

CraigeCraige

2,8522 gold badges19 silver badges28 bronze badges

There is most likely no difference. Optimization on this level does usually not make any sense in an interpreted language like PHP.

In most cases, your logic will require you to put the block inside the loop anyway. Otherwise, the loop will continue even if an error has occurred.

answered Jan 12, 2011 at 20:09

PekkaPekka

434k137 gold badges964 silver badges1077 bronze badges

Of course, there's a difference, in the most obvious way int the first case you will only check for errors before entering the loop, if the loop doesn't have exception throwers, leave it that way. In the other hand you will be checking it in each iteration, wich you'll need if you have sentences or methods ... wich can have exceptions.

I'dont know if i explain myself well, let me know if you understand

answered Jan 12, 2011 at 20:11

Not the answer you're looking for? Browse other questions tagged php performance try-catch or ask your own question.

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

Examples

Example #4 Throwing an Exception

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #5 Exception handling with a finally block

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

The above example will output:

Example #7 Nested Exception

The above example will output:

Example #8 Multi catch exception handling

The above example will output:

Example #9 Omitting the caught variable

Only permitted in PHP 8.0.0 and later.

Chủ Đề