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{
}
If anyone can tell me what is wrong in the answer I thank you and the community will win.
– Maniero
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)
– Vitor Couto
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.
– Maniero