Thaninrat
Thaninrat

Reputation: 11

Try catch in PHP, Can I go this way?

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)

Upvotes: 0

Views: 695

Answers (1)

cweiske
cweiske

Reputation: 31078

Yes, you can do that.

Just go and try it out yourself.

Upvotes: 2

Related Questions