My stackoverflow answer #1

by krike in Other / Q&A on 24 Aug 2010

Stackoverflow is one of the websites I visit the most because it’s a place where I can get help really fast but it’s also a place where I can help other people. Therefore I will feature one of my answers each week and who knows it might help you out as well.

The question

This weeks question by RPK:

I have various functions in a class. In each function I use try…catch. Is there any way to simplify this? I want to make one error class and it must be accessible from any file in my project. I don’t want to use try..catch in each function, rather it should be automatically directed to the Error class.

My anwser

do not add the try catch in the function itself but in the page where the function is called.

        $faq_title = mysqli_real_escape_string($link, $_POST['faq_title']);
        $faq_subtitle = mysqli_real_escape_string($link, $_POST['faq_subtitle']);
        $desc = mysqli_real_escape_string($link, $_POST['desc']);
        $faq_e = new Shopadmin();
        $faq_e->add_faq($faq_title, $faq_subtitle, $desc);
        $feedback = "<div class='succes'>FAQ added succesfully!</div>";
catch(Exception $e)
        $feedback = "<div class='error'>";
        $feedback .= $e->getMessage();
        $feedback .= "</div>";

and in my function I check if the query was done succesfully or not, if not I throw a new exception which will be catched and stored into $feedback which I echo out on the main container div.

this way you can call for different functions withouth having to add the try catch in each function

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.