Skip to content

Instantly share code, notes, and snippets.

@jaytaph
Last active December 12, 2015 10:39
Show Gist options
  • Save jaytaph/4760843 to your computer and use it in GitHub Desktop.
Save jaytaph/4760843 to your computer and use it in GitHub Desktop.
<?php
function foobar($filename) {
$f = fopen($filename, "r");
if (! $f) throw new Exception("Cannot open file $filename");
// Do stuff, maybe throw some exceptions
}
try {
$tmp = foobar("/my/file");
} catch (Exception $e) {
print "An error has occurred. Using default values";
$tmp = "somedefaultvalue";
}
<?php
try {
print "this is our try block\n";
throw new Exception();
} catch (Exception $e) {
print "something went wrong\n";
} finally {
print "This part is always executed\n";
}
/* Output:
this is our try block
something went wrong
This part is always executed
*/
<?php
// Runtime Exception is not caught by the catch-blocks
try {
print "this is our try block\n";
throw new RuntimeException();
} catch (LogicException $e) {
print "something logical went wrong\n";
} catch (BadMethodCallException $e) {
print "something made a bad method call\n";
} finally {
print "This part is always executed\n";
}
/* Output:
this is our try block
This part is always executed
Fatal error: Uncaught exception 'RuntimeException' in 003.php:6
Stack trace:
#0 {main}
thrown in 003.php on line 6
*/
<?php
function foo() {
try {
print "Try block\n";
throw new RuntimeException("foobar!");
} catch (LogicException $e) {
print "Exception raised: " . $e->getMessage() . "\n";
} finally {
print "Finally, some cleanup!\n";
}
}
try {
foo();
} catch (RuntimeException $e) {
print "outer exception: " . $e->getMessage() . "\n";
} finally {
print "Outer finally\n";
}
/* Output:
Try block
Finally, some cleanup!
outer exception: foobar!
Outer finally
*/
<?php
function foobar() {
try {
$a = 42;
return $a;
} catch (Exception $e) {
print "Exception!\n";
} finally {
print "Finally called!\n";
}
return -1;
}
print foobar() . "\n";
/* Output:
Finally called!
42
*/
<?php
function foobar() {
try {
throw new Exception();
return 1;
} catch (Exception $e) {
print "Exception!\n";
return 2;
} finally {
print "Finally called!\n";
return 3;
}
return -1;
}
print foobar() . "\n";
/* Output:
Exception!
Finally called!
3
*/
<?php
function bar1() {
print "bar1 called\n";
return 1;
}
function bar2() {
print "bar2 called\n";
return 2;
}
function bar3() {
print "bar3 called\n";
return 3;
}
function foobar() {
try {
throw new Exception();
return bar1();
} catch (Exception $e) {
print "Exception!\n";
return bar2();
} finally {
print "Finally called!\n";
return bar3();
}
return -1;
}
print foobar() . "\n";
/* Output:
Exception!
bar2 called
Finally called!
bar3 called
3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment