Try catch in PHP, Can I go this way? - php

I writing a script which has to read content from URL all the time. Instead of ...
// block 1
Try{
if(!someAction1){
throw new exception(someException1);
}
}catch(Exception $e){
//exception handling code
}
// block 2
Try{
if(!someAction2){
throw new exception(someException2);
}
}catch(Exception $e){
//exception handling code
}
// block 3
Try{
if(!someAction3){
throw new exception(someException3);
}
}catch(Exception $e){
//exception handling code
}
Can I change in to this ...
Try{
someFunction1()
}catch(Exception $e){
//exception handling code
}
public someFunction1(){
if(!someAction1){
throw new Exception(someException1);
}
if(!someAction2){
throw new Exception(someException2);
}
someFunction2()
}
public someFunction2(){
if(!someAction3){
throw new Exception(someException3);
}
}
The reasone I want to do this because there are a lot of try-catch block to create. But all of them only to prevent the script from stopping itself (I'm running it with Crontab). The exception handling code is simple, write the error log file (Same for every try-catch block)

Yes, you can do that.
Just go and try it out yourself.

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

PHP try-catch some problems

Hello. Is it possible to use such code in PHP?
try {
throw new InternalException('Internal');
} catch (InternalException $e) {
throw new Exception('Internal To global');
} catch (Exception $e){
print $e->getMessage();
}
class InternalException extends Exception {
// some code here
}
Nest multiple try...catch instead.
try {
throw new InternalException('Internal');
} catch (InternalException $e) {
try {
throw new Exception('Internal To global');
} catch (Exception $e){
print $e->getMessage();
}
}
class InternalException extends Exception {
// some code here
}
See PHP: Exceptions - Manual
It does not make sense to "transform" Exceptions. Don't throw em if you won't handle them.
You can catch different Exceptions this way:
try {
throw new InternalException();
} catch (HardwareException $e) {
} catch (InternalException $e) {
// this catch block will be executed
} catch (Exception $e) {
// all other exceptions
}
Yes, you can catch specific exceptions separately.
Exceptions are only caught if they're thrown in try blocks. Exceptions thrown in catch blocks are not caught within other sibling catch blocks of the same try..catch statement. You have to nest the whole thing in another outer try..catch block to catch those.

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.';
}

Is it possible to have Try/Catch Throw with multiple exceptions

i have the following code and i'm wondering if i can use try & catch as below:
class fun_database implements idbInfo{
private $srvr=idbInfo::srvr_name;
private $usr=idbInfo::usrnm;
private $pass=idbInfo::psswrd;
private $db=idbInfo::db_name;
public function connct(){
$hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db);
if ($hookup->connect_errno)
{
throw new Exception("Error Processing Request", 1);
}
}
public function sql_require_all($table_name, $table_col){
$hookup = new connct();
$result = $hookup->query("SELECT $table_col FROM $table_name");
if($hookup->error()){
throw new Exception("Error Processing Request", 1);
}
return $result->num_rows;
}
}
This is a simple connection to the mysql and performing some querying there. Here is and the actual call of the functions above:
$conn = new fun_database();
try{
$result = $conn->sql_require_all('wordtypes', 'types');
}
catch(Exception $err){
echo "Problems at:". $err->getMessage();
}
return "<option>".$result."</option>";
What i'm asking is a bit theory. Most probably this code is NOT WORKING (i didn't test it yet). I just want to know is it possible with one 'try' to 'catch' two exceptions (as you can see the first 'throw' is in the second method of fun_database, and the second 'throw' is in the first method of the same object which is only called from the second method).
sorry for making it too complicated but still can't figure it out id this structure of try/catch is working.
you can only catch different types of exception...
class fun_database implements idbInfo{
private $srvr=idbInfo::srvr_name;
private $usr=idbInfo::usrnm;
private $pass=idbInfo::psswrd;
private $db=idbInfo::db_name;
public function connct(){
$hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db);
if ($hookup->connect_errno)
{
throw new DomainException("Error Processing Request", 1);
}
}
public function sql_require_all($table_name, $table_col){
$hookup = new connct();
$result = $hookup->query("SELECT $table_col FROM $table_name");
if($hookup->error()){
throw new Exception("Error Processing Request", 1);
}
return $result->num_rows;
}
}
Then:
try{
$conn = new fun_database();
$result = $conn->sql_require_all('wordtypes', 'types');
}
catch(DomainException $err){
echo "This Problem at:". $err->getMessage();
}
catch(Exception $err){
echo "That Problem at:". $err->getMessage();
}
return "<option>".$result."</option>";
you would need your class instantiation inside that try block though I believe.
It wouldn't catch the two exceptions because as soon as the first exception is thrown, it goes straight to the catch block, thereby skipping the second exception directly.
You could wrap each code which may throw an exception in its own try-catch block.
Yes and no. Your code is able to catch two of this exceptions but not both of them at the same time. When one of exception will be thrown, program execution will look for closest catch block, which fits to catch Exception class. Rest of code will be omitted.
You can throw an exception at an point in the program (not after an excpetion if it is not caught).
As soon as it hits this point it will stop and try to make the fallback to the a try catch block. As soon as it finds one it will do this block (if it is a good catch)
You could make a try catch around your entire program or just a function.
You can throw different classes of exceptions:
class ConnectException extends Exception {}
class QueryException extends Exception {}
and then catch different exceptions:
try {
// something
}
catch (ConnectException $ex) {
// connect exception
}
catch (QueryException $ex) {
// query exception
}
It is not possible because when you throw
throw new Exception("Error Processing Request", 1);
this exception it will be caught in this line
catch(Exception $err){
echo "This Problem at:". $err->getMessage();
}
you will not reach the line that can throw the other exception if first exception was thrown

PHP exception catching and programming logic

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.

Categories