PHP - catch an exception within an included document - php

I have a number of files that are included (with "include_once") in my code and I want to control exceptions at the top level of my "index" file.
But, try/catch statements do not capture exceptions generated in an included file. For instance, an exception in my children files will be unhandled.
Can anyone please point me in the right direction?
index.php:
try
{
include_once( "child.php" );
}
catch(Exception $e)
{
// do something....
}
child.php
throw new Exception ("error!");

Try this :
index.php
<?php
try
{
include_once( "child.php" );
} catch(Exception $e) {
echo $e->getMessage();
}
child.php
<?php
throw new Exception ("error!");

Related

Kill Script using die() but still show footer (require)

I have require statements for my header and footer:
<?php
require "assets/php/header.php";
// Script goes here.
require "assets/php/footer.php";
?>
If I have a script in between the two statements, how can I have a die() statement in the script to end the current script, but still show the footer? If there is no way of doing this, is there any alternatives? I personally think that the require statements are obsolete, and I would love to know of some alternatives, or just a better way of setting it up. Thanks in advance.
You should use exception.
Try something like this :
<?php
try {
require "assets/php/header.php";
// Script goes here.
// replace "die();" with :
throw new Exception("I want to die");
// folowing code executed if no exception is thrown
require "assets/php/footer.php";
// end of "normal" case
} catch (Exception $e) {
// an exception makes footer and then dies
require "assets/php/footer.php";
die();
}
?>
you can also use this catch if you use Exception that mustn't trigger footer :
} catch (Exception $e) {
if($e->getMessage() == "I want to die") {
// an exception asks to make footer and then dies
require "assets/php/footer.php";
die();
} else {
throw $e;
}
}
Or if you want to make it clean, make a new exception class (for instance DieWithFooterException) and use it like this :
<?php
try {
require "assets/php/header.php";
// Script goes here.
// replace "die();" with :
throw new DieWithFooterException();
// folowing code executed if no exception is thrown
require "assets/php/footer.php";
// end of "normal" case
} catch (DieWithFooterException $dwfe) {
// an exception asks to make footer and then dies
require "assets/php/footer.php";
die();
} catch (Exception $e) {
// stuff to do with other excpetions
}
?>
This said, the last solution is the nicer way to do it :)

PHP exception inside catch: how to handle it?

Suppose to have a PHP code inside a try...catch block. Suppose that inside catch you would like to do something (i.e. sending email) that could potentially fail and throw a new exception.
try {
// something bad happens
throw new Exception('Exception 1');
}
catch(Exception $e) {
// something bad happens also here
throw new Exception('Exception 2');
}
What is the correct (best) way to handle exceptions inside catch block?
Based on this answer, it seems to be perfectly valid to nest try/catch blocks, like this:
try {
// Dangerous operation
} catch (Exception $e) {
try {
// Send notification email of failure
} catch (Exception $e) {
// Ouch, email failed too
}
}
You should not throw anything in catch. If you do so, than you can omit this inner layer of try-catch and catch exception in outer layer of try-catch and process that exception there.
for example:
try {
function(){
try {
function(){
try {
function (){}
} catch {
throw new Exception("newInner");
}
}
} catch {
throw new Exception("new");
}
}
} catch (Exception $e) {
echo $e;
}
can be replaced to
try {
function(){
function(){
function (){
throw new Exception("newInner");
}
}
}
} catch (Exception $e) {
echo $e;
}
You have 2 possible ways:
You exit the program (if it is severe) and you write it to a log file and inform the user.
If the error is specifically from your current class/function,
you throw another error, inside the catch block.
You can use finally. Code in this branch will be executed even if exception is thrown within catch branch

How do I handle error message in my case

I am trying to catch an error with php when I connect to DB
I have something like
try{
//connect to DB
}catch(exception $e){
echo $e
}
//other php codes...
//My html elements...
<div>....
My problem is that I want to skip //other phpo codes if we have error connecting to DB and straight to show my html elements. Is that possible to do it? Thanks a lot.
Just out that code in your try/catch. Once the exception is thrown execution is handed off to the catch portion of the control structure and that portion of code is never reached:
try{
//connect to DB
// If an exception is throw above we never get here
//other php codes...
}catch(exception $e){
echo $e
}
//My html elements...
<div>....
If you don't want to move the // other php code
And you don't want/can't edit the try/catch block, surely the try/catch returns some variable you can test, even if only that $e.
try {
// something like $connected_db should be available
}
catch (exception $e)
{
}
if (!empty($connected_db) AND empty($e)) // one or the other depending on the code above
{
// other php code
}
// my html elements

What's the `finally` keyword for in PHP?

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.

How can I use an exception without the script dying?

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

Categories