简体   繁体   中英

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)

Yes, you can do that.

Just go and try it out yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM