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";
}
Related
$row=mysql_fetch_array($result, MYSQL_ASSOC) or die(mysql_error())
In this code the mysql_error will be displayed if mysql_fetch_array fails. Is there any way to throw that mysql_error to reload a page instead.
P.S.: I know mysql has been depreciated. Its an old project so please don't suggest in your answers to use mysqli and PDO. I am well aware of it. Please tell me the way to throw reload page as error.
You could use try catch for exception handling in PHP
http://www.php.net/manual/en/language.exceptions.php
try
{
// do something that can go wrong
}
catch (Exception $e)
{
throw new Exception( 'Something wrong', 0, $e);
}
OR
try
{
// do something that can go wrong
}
catch (Exception $e)
{
if ($e instanceof CustomException)
{
// do something
}
else if ($e instanceof OtherException)
{
// do something
}
else
{
// do something
}
}
Or
try
{
}
catch (CustomException $e)
{
}
catch (OtherException $e)
{
}
catch (Exception $e)
{
}
Is this possible in PHP?
try {
$obj = new Clas();
if ($obj->foo) {
// how to exit from this try block?
}
// do other stuff here
} catch(Exception $e) {
}
I know I can put the other stuff between {}, but that increases indenting on a bigger code block and I don't like it :P
With a goto of course!
try {
$obj = new Clas();
if ($obj->foo) {
goto break_free_of_try;
}
// do other stuff here
} catch(Exception $e) {
}
break_free_of_try:
Well, there is no reason for that, but you can have fun forcing an exception in your try block, stopping execution of your function.
try {
if ($you_dont_like_something){
throw new Exception();
//No code will be executed after the exception has been thrown.
}
} catch (Exception $e){
echo "Something went wrong";
}
I also faced this situation, and like you, didn't want countless if/else if/else if/else statements as it makes the code less readable.
I ended up extending the Exception class with my own. The example class below was for validation problems that when triggered would produce a less severe 'log notice'
class ValidationEx extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
In my main code I call it;
throw new ValidationEx('You maniac!');
Then at the end of the Try statement I have
catch(ValidationEx $e) { echo $e->getMessage(); }
catch(Exception $e){ echo $e->getMessage(); }
Happy for comments and criticisms, we're all here to learn!
try
{
$object = new Something();
if ($object->value)
{
// do stuff
}
else
{
// do other stuff
}
}
catch (Exception $e)
{
// handle exceptions
}
Couldn't you just do like this?
try{
$obj = new Clas();
if(!$obj->foo){
// do other stuff here
}
}catch(Exception $e){
}
In php 5.3+ the nice thing about using exceptions with a try catch block, is that you can make your own Exceptions and handle them how and when you want. See: Extending Exceptions
class AcceptedException extends \Exception
{
//...
}
You can then catch specific exceptions or use if ($e instanceof AcceptedException) within your catch \Exception block to determine how you want to handle the exception(s).
Handled Example: http://ideone.com/ggz8fu
Unhandled Example: http://ideone.com/luPQel
try {
$obj = (object) array('foo' => 'bar');
if ($obj->foo) {
throw new \AcceptedException;
}
} catch (\AcceptedException $e) {
var_dump('I was accepted');
} catch (\Exception $e) {
if ($e instanceof \InvalidArgumentException) {
throw $e; //don't handle the exception
}
}
This makes your code much more readable and easier to troubleshoot as opposed to a lot of alternative solutions.
Personally I like to exit try/catch statements by using a
throw new MyException("optional message", MyException::ERROR_SUCCESS);
which I obviously catch by using:
switch($e->getCode()) {
/** other cases make sense here */
case MyException::ERROR_SQL:
logThis("A SQL error occurred. Details: " . $e->getMessage());
break;
case MyException::ERROR_SUCCESS:
logThis("Completed with success. Details: " . $e->getMessage());
break;
case MyException::ERROR_UNDEFINED:
default:
logThis("Undefined error. Details: " . $e->getMessage());
break;
}
This is the way I'd do that :
<?php
echo 'this' . PHP_EOL;
switch(true) {
default:
try {
echo 'is' . PHP_EOL;
break;
echo 'not' . PHP_EOL;
} catch (Exception $e) {
// error_log($e->getMessage());
}
}
echo 'fun !';
:-)
I have a situation where it would be nice to be able to have a catch block where the type of the Exception is determined at run time. It would work something like this:
$someClassName = determineExceptionClass();
try {
$attempt->something();
} catch ($someClassName $e) {
echo 'Dynamic Exception';
} catch (Exception $e) {
echo 'Default Exception';
}
Is this at all possible?
That doesn't work as far as I'm aware. You could mimic that functionality with a control statement like this:
$someClass = 'SomeException';
try
{
$some->thing();
}
catch (Exception $e)
{
switch (get_class($e))
{
case $someClass:
echo 'Dynamic exception.';
break;
default:
echo 'Normal exception.';
}
}
Let's say I have codes like this:
try{
doTaskA();
doTaskB();
doTaskC();
} catch(MyException $e){
fixMyException();
}
When doTaskA() throws MyException, I want the program to go through fixMyException(), then it goes back and continues executing doTaskB() and doTaskC(). Is it possible?
The same thing should apply to other tasks, i.e. all doTaskA/B/C() may throw the same exception, and I want the program can go on to the unfinished tasks every time after it executes fixMyException()..
Is there any thing like "continue" or "resume" function in the exception handling?
I have checked the PHP manual but it seems such control structure doesn't exist. If so, what's the best practice to design the program that can do what I want? (Supposed I have over 10 taskes inside the try block).
function do_all_tasks($position=0)
{
$tasks = array('doTaskA', 'doTaskB', 'doTaskC', ...);
$size = count($tasks);
for ($i=$position; $i<$size; ++$i)
{
try
{
$func = $tasks[$i];
$func();
}
catch (Exception $e)
{
fixMyException();
do_all_tasks($i+1);
};
}
}
do_all_tasks();
try{
doTaskA();
} catch(MyException $e){
fixMyException();
}
try{
doTaskB();
} catch(MyException $e){
fixMyException();
}
try{
doTaskC();
} catch(MyException $e){
fixMyException();
}
How is that any different than doing
try {
doTaskA();
} catch (MyException $e) {
fixMyException();
}
try {
doTaskB();
} catch (MyException $e) {
fixMyException();
}
try {
doTaskC();
} catch (MyException $e) {
fixMyException();
}
No it is not possible. You'd need to put each of doTask*() functions in it's own separate try-catch block.
I am trying to pass an exception from a specific catch block to a more general catch block. However it does not appear to be working. I get a 500 server error when I try the following. Is this even possible?
I realize that there are easy workarounds, but isn't it normal to say, "Hey I don't feel like dealing with this error, let's have the more general exception handler take care of it!"
try {
//some soap stuff
}
catch (SoapFault $sf) {
throw new Exception('Soap Fault');
}
catch (Exception $e) {
echo $e->getMessage();
}
Technically this is what you're looking for:
try {
try {
//some soap stuff
}
catch (SoapFault $sf) {
throw new Exception('Soap Fault');
}
}
catch (Exception $e) {
echo $e->getMessage();
}
however I agree that exceptions shouldn't be used for flow control. A better way would be like this:
function show_error($message) {
echo "Error: $message\n";
}
try {
//some soap stuff
}
catch (SoapFault $sf) {
show_error('Soap Fault');
}
catch (Exception $e) {
show_error($e->getMessage());
}