You cannot explicitly state (checked Exception) that a function can cast an exception because PHP is not Java, the only language that allows it, and it did not work.
You can make an exception as simple as possible, but if you do this you will be programming like Java, so if you want to code in Java, go to Java.
Technically you can do this:
public function calcularMedia($valor) {
if ($valor < 0) throw new ValorNegativoException();
return $valor > 6 ? "Passou" : "Recuperação";
}
You would have to create your own exception for this. If you’re not gonna do it right then why use this mechanism?
Some people would rather do this, but it’s abuse of the mechanism:
public function calcularMedia($valor) {
if ($valor < 0) throw new Exception("Valor Negativo");
return $valor > 6 ? "Passou" : "Recuperação";
}
You can at least make a compromise, in some cases it’s ok:
public function calcularMedia($valor) {
if ($valor < 0) throw new InvalidArgumentException("Valor Negativo");
return $valor > 6 ? "Passou" : "Recuperação";
}
But PHP might just be:
public function calcularMedia($valor) {
if ($valor < 0) return false;
return $valor > 6 ? "Passou" : "Recuperação";
}
I put in the Github for future reference.
Then you test if it came false
and doesn’t need a try-catch
, you only accept a value if it is different from false
. It is more correct because you expect it to happen, it is not an exceptional situation.
If you don’t understand very deeply how to use exception correctly it is better not to use, because PHP was created all without thinking about it. It is true that lately they are encouraging more its use, which makes the language lose identity and starts to become Java. Java is a much better Java than PHP. PHP is a phenomenal PHP and exception should be something exceptional in code. Even Java has moved away from exception.
You can read more on:
Do you want to throw an exception or declare that the function can throw an exception? They are two completely different things. If you want to launch, do you have any specific questions? After all, just launch.
– Maniero
Good question @Maniero, can you make an answer with the 2 things if possible I don’t know what the difference is? My question is whether where there is "CAST EXCEPTION", I can return a
throws Exception
.– Ricardo Lucas