Create and implement Exceptions in PHP

Asked

Viewed 301 times

1

I’m trying to learn to deal with Exceptions in PHP, but not just using Exception default. To solve my challenge, I need to create two Exceptions and fire them in two specific situations. Follow the code:

Main code where exceptions will be called

include("./testeA.php");
include("./exceptions.php");
$testeA = new TesteA(3);

try {
    $testeA->addName("steve rogers");
    $testeA->addName("Bruce banner");
    $testeA->addName("anthony Edward");
    echo $testeA->getNames();

} catch(LimitNameException $e){
    echo "Você não pode adicionar mais do que 
    {$testeA->getLimitNames()} nomes";
} catch(InvalidNameException $e){
    echo "Você deve inserir um nome válido";
} catch(Exception $e){
    echo "Ocorreu um erro inesperado";
}

Class TesteA (here may have some errors of logic and missing things to implement)

class TesteA
{
    public $nameArray = array();
    public $maxSize;

    function __constructor($maxSize){
        $this->maxSize = $maxSize;
    }


    public function addName($name){   
        array_push($this->nameArray, $name);      
    }


    public function getNames(){
        for($count= 0; $count<sizeof($this->nameArray); $count++){
            echo $count+1 .". ". $this->nameArray[$count] ."<br>";
        }
    }

    public function getLimitNames(){
        return $this->maxSize;
    }
}

Filing cabinet exceptions (here I have no idea how to use the classes, I gave a read in the documentation of PHP and other similar questions here in Sopt, but I could not understand and apply clearly)

class LimitNameException extends Exception{

}
class  InvalidNameException extends Exception{

}

1 answer

2


Exception is something overrated. They are less useful than people think and almost everyone uses wrong. I talk about it a lot here on the site. In PHP, a language of script, it makes even less sense, but how people started to use it as if it were a language Nterprise, let’s talk about it. Note that the first link there shows other better mechanisms to deal with this situation.

You’re already above average that you know Exception is not good and only should capture in last case (although I would not put there where put because will have to repeat this code everywhere without need, interestingly this mechanism exists precisely not to have to keep repeating, but is what people do).

Looking at the links above you will see that I and many people consider the use of exception for flow control, to indicate failure in business rule, as something very wrong, and that is what you are doing. At least he made the exception more specific. There’s still the problem of wanting to wear something because everyone’s wearing it, even if they have no idea why they’re doing it, or even if it’s really good.

Almost always talking about exception without a very specific context can give wrong understanding of how to use, but come on, would do so:

public function addName($name) {
    if (len($name) > $this->getLimitNames()) throw new LimitNameException();
    if ($name == ????) throw new InvalidNameException();
    array_push($this->nameArray, $name);      
}

I put in the Github for future reference.

So since you are mistakenly using the exception for validation you should validate if you are within the established condition (I don’t have the requirements so I kicked one and only started another) and if you are not, you should launch the exception.

You should probably write some extra logic inside the exception itself, and maybe get some argument that gives more information about what happened, who knows for example put error message and even with the limit that should have used (including because the shape made would probably already be considered abstraction leak), but without knowing the requirements I have no way to do much, I’m just answering the specific question.

It is not even this case that is too artificial, but usually the exception makes much more sense in the constructor since it has no other way to communicate a possible error, which makes some say that it is not a good construction to use.

Without a very large domain, almost all mechanisms, especially the most complex ones, should be avoided. Writing the right code is much more complicated than it seems, but what matters most is understanding where you want to get at, then understanding why there is each mechanism or technique, to only use what really meets the need without causing other problems. Using the mechanism is the easy part, understanding every process that involves it is more complicated.

  • If anyone can tell me what is wrong in the answer I thank you and the community will win.

  • Thank you very much for the reply, even had read some of your answers about Exception here at Sopt! The problem is that in this case I am obliged to use Exception because it is a proof that, at the very least, I understand about and I know how to apply if necessary (regardless of whether it is being used correctly or not, as you said)

  • What you said is inconsistent. You have to know how to apply even if you should not apply. To know is to apply is to know when not to apply. It seems to me a proof that proves nothing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.