質問

Consider these two examples

<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

try {
    throw_exception();
} catch (Exception $e) {
    echo $e->getMessage();
}

some_code();

// More arbitrary code
?>

and

<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

try {
    throw_exception();
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    some_code();
}

// More arbitrary code
?>

What's the difference? Is there a situation where the first example wouldn't execute some_code(), but the second would? Am I missing the point entirely?

役に立ちましたか?

解決

If you catch Exception (any exception) the two code samples are equivalent. But if you only handle some specific exception type in your class block and another kind of exception occurs, then some_code(); will only be executed if you have a finally block.

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
}

some_code(); // Will not execute if throw_exception throws an ExceptionTypeB

but:

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
} finally {
    some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}

他のヒント

fianlly block is used when you want a piece of code to execute regardless of whether an exception occurred or not...

Check out Example 2 on this page :

PHP manual

Finally will trigger even if no exception were caught.

Try this code to see why:

<?php
class Exep1 extends Exception {}
class Exep2 extends Exception {}

try {
  echo 'try ';
  throw new Exep1();
} catch ( Exep2 $e)
{
  echo ' catch ';
} finally {
  echo ' finally ';
}

echo 'aftermath';

?>

the output will be

try  finally 
Fatal error: Uncaught exception 'Exep1' in /tmp/execpad-70360fffa35e/source-70360fffa35e:7
Stack trace:
#0 {main}
  thrown in /tmp/execpad-70360fffa35e/source-70360fffa35e on line 7

here is fiddle for you. https://eval.in/933947

From the PHP manual:

In PHP 5.5 and later, 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.

See this example in the manual, to see how it works.

http://www.youtube.com/watch?v=EWj60p8esD0

Watch from: 12:30 onwards

Watch this video. The language is JAVA though. But i think it illustrates Exceptions and the use of finally keyword very well.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top