Question

I've got an Input helper class that throws an exception if the source array index is undefined.

So if I had something like:

$input = new Input($_GET, $_POST);

$input->get("var1");
$input->get("var2");
$input->get("var3");
$input->get("var4");

It would now be:

$input = new Input($_GET, $_POST);

try {
    $input->get("var1");
} catch(Exception $e) {
    //handle it
}

try {
    $input->get("var2");
} catch(Exception $e) {
    //handle it
}

try {
    $input->get("var3");
} catch(Exception $e) {
    //handle it
}

try {
    $input->get("var4");
} catch(Exception $e) {
    //handle it
}

I have no idea how I could use less try catch blocks without having to stop execution of the further code if I was to put everything in 1 try catch block.

Is this the correct way of using the try catch function?

Était-ce utile?

La solution 2

Do you really need to handle every exception individually? e.g. would

try {
   $input->get('var1');
   $input->get('var2');
   $input->get('var3');
   $input->get('var4');
} catch (Exception $e) {
  ... do something
}

work just as well? With this construct, any of the get() calls that fail would trigger the catch and further get() calls will not be performed. e.g if var2 throws, then var3 and var4 will never be gotten.

Autres conseils

Why not this:

try {
    $input->get("var1");
    $input->get("var2");
    $input->get("var3");
    $input->get("var4");
} catch(Exception $e) {
    //handle it
}

I woudn't add so many try catches. It's a pain to develop and maintain. You will thank yourselfs if you can push it back to one method.

Even better what i would recommend is:

if(isset($input->get("var4")))
$input->get("var4")

or

function get($name){
 if(isset($this->get($name)))
   return $this->get($name);

 return false; //or throw an exception/error here :)
}

It depends on what you'd like to achieve. If you'd like to break code execution after any of getters fail, you should use HeroFTime solution. If you'd like to handle each getter separately it's better to write a function that encapsulates the try/catch as follows:

function getter($input, $value) {
  try {
     return $input->get($value);
  } catch(Exception $e) {
     return null; // or any default value you'd like to provide
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top