PHP exception catching and programming logic - php

I am trying to catch an error on object creation, because this object can and should sometimes throw an error.
try {
$obj = new MyObject();
} catch (Exception $e) {
echo 'Caught exception: ';
}
I want to do a lot of things with this new object, but only IF it was created without throwing an exception.
The problem is that I do not wish to do all these things inside the try catch block. How would I accomplish this?
Thanks a lot
Michael

I really can't see any reason for what you are asking, but maybe the best thing is to do all the other stuff in a function that you call from the try/catch block...
function allMyStuff($obj){
// do some stuff to $obj here
}
try {
$obj = new MyObject();
allMyStuff($obj);
} catch (Exception $e) {
echo 'Caught exception: ';
}
Otherwise, to do literally as you seem to be asking, you could set a switch before the try/catch block to on, and set it to off in the catch block. That way you can test the switch to see whether to execute all your other stuff.
$mySwitch = true;
try {
$obj = new MyObject();
} catch (Exception $e) {
echo 'Caught exception: ';
$mySwitch = false;
}
if($mySwitch){
// do some stuff here
}

There's no point in doing it outside. It also makes more sense to do all of your actions inside the try/catch block to test it for errors.
You should keep it inside the try/catch block as it is exactly what it was designed for.

Slightly odd - but you could either die or redirect...
try {
$obj = new MyObject();
} catch (Exception $e) {
die("Caught exception: {$e->getMessage()}");
}
//program continues as it hasn't "died"
or...
try {
$obj = new MyObject();
} catch (Exception $e) {
header("Location:/exceptionHandler.php?e=" . rawurlencode(serialize($e)));
die();
}
//program continues as it's not been redirected or "died"
... though as everyone else has said - it probably still makes more sense to wrap the whole kaboodle in a try ... catch block.

Related

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

Get all the exceptions from one try catch block

I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}

How to pass the exception caught in inner catch to outer catch in a nested try catch

I am nesting try catches inside of a main try catch statement, what I would like to know is how I can make the main try catch fail if one of the nested try catches fails?
Here is my code:
try
{
try
{
//how can I make the main try catch fail if this try catch fails?
}
catch(Exception $e)
{
error_log();
}
}
catch(Exception $e)
{
error_log();
}
After error_log(); in the first try-catch, type throw $e; (on a new line). This will throw the error again, and the outer try-catch will handle it.
You should extend Exception for the various different types of Exception. That way you can trigger a specific try-catch block:
try
{
...
try
{
throwSomeException();
}
catch ( InnerException $e )
{
...do stuff only for InnerException...
}
...
}
catch ( Exception $e )
{
...do stuff for all types of exception...
}
Additionally, you can chain your catch statements to trigger different blocks in a single try-catch:
try
{
...
}
catch ( SpecificTypeOfException $e )
{
..do something specific
}
catch ( TypeOfException $e )
{
..do something less specific
}
catch ( Exception $e )
{
..do something for all exceptions
}
Inside the inner catch, throw() - NOT recommended, I've seen several issues with PHP when doing this. Or set a flag to throw just after the inner catch.
Here's an example throwing the same exception (or you could throw a different one).
try {
$ex = null;
try {
//how can I make the main try catch fail if this try catch fails?
} catch(Exception $e){
$ex = $e;
error_log();
}
if ($ex) {
throw $ex;
}
} catch(Exception $e){
error_log();
}
I handle exceptions in a way similar to eventHandling in Javascript.
An event bubbles up the ladder from specific to generic. When it reaches the start program, an exception lost all it's meaning to the code and should simply be caught for logging and ending an application.
In the meantime a lot of stuff can happen
CallStack:
Start Lunch
Eat Apple (Before this code, an apple was bought as lunch)
Sink teeth in apple
During my eating of the apple, a worm appeared:
throw NausiaException('I found a bleeding worm...');
Eat Apple scope catches
catch(Exception $e)
the exception because in that scope we can return the apple to the store and shout at the manager. Since nothing more useful can be said about the occurrence,
throw $e
is called because eating the apple failed.
Something could've gone different
However, if the store manager refused to refund, you can wrap the exception
throw new RefundFailedException('The manager is a cheap skate', RefundFailedException::REFUSED, $e)
Start lunch Scope
Start lunch scope wants to throw away bad lunch
try {
//Start lunch
} catch (Exception $e) {
switch (true) {
case $e instanceof NausiaException:
case $e instanceof RefundFailedException:
//Throw lunch away
break;
}
}
use of a bool variable and "return" keyword at appropriate place could do the trick for you...

php try ... else

Is there something similar in PHP to the try ... else in Python?
I need to know if the try block executed correctly as when the block executed correctly, a message will be printed.
PHP does not have try/catch/else. You could however set a variable in the catch block that can be used to determine if it was run:
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
I think the "else" clause is a bit limiting, unless you don't care about any exceptions thrown there (or you want to bubble those exceptions)... From my understanding of Python, it's basically the equivalent of this:
try {
//...Do Some Stuff Here
try {
// Else block code here
} catch (Exception $e) {
$e->elseBlock = true;
throw $e;
}
} catch (Exception $e) {
if (isset($e->elseBlock) && $e->elseBlock) {
throw $e;
}
// catch block code here
}
So it's a bit more verbose (since you need to re-throw the exceptions), but it also bubbles up the stack the same as the else clause...
Edit Or, a bit cleaner version (5.3 only)
class ElseException extends Exception();
try {
//...Do Some Stuff Here
try {
// Else block code here
} catch (Exception $e) {
throw new ElseException('Else Clasuse Exception', 0, $e);
}
} catch (ElseException $e) {
throw $e->getPrevious();
} catch (Exception $e) {
// catch block code here
}
Edit 2
Re-reading your question, I think you may be overcomplicating things with an "else" block... If you're just printing (which isn't likely to throw an exception), you don't really need an else block:
try {
// Do Some stuff
print "Success";
} catch (Exception $e) {
//Handle error here
print "Error";
}
That code will only ever print either Success or Error... Never both (since if the print function throws the exception, it won't be actually printed... But I don't think the print CAN throw exceptions...).
Not familiar with python but it sounds like you're after Try Catch blocks used with exceptions...
http://php.net/manual/en/language.exceptions.php
There is try-catch in php.
Example:
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else 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';
try {
$clean = false;
...
$clean = true;
} catch (...) { ... }
if (!$clean) {
//...
}
That's the best you can do.
You can use try { } catch () { } and throw. See http://php.net/manual/en/language.exceptions.php
try {
$a = 13/0; // should throw exception
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
or manually:
try {
throw new Exception("I don't want to be tried!");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

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