Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some people return after they throw Exceptions?

Tags:

exception

php

I see in some of the code on Github

if($something_funky_happens){   throw new \LogicException(...);   return; } 

Is this required, or it is not important to return? because I know that after you throw exceptions the script stops, so further code does not run

like image 415
Alex Avatar asked Jul 18 '12 18:07

Alex


People also ask

Do you need to return after throwing an exception?

After throwing an exception, you do not need to return because throw returns for you. Throwing will bubble up the call stack to the next exception handler so returning is not required.

What does method return if exception is thrown?

Yes, throwing an exception causes the method to return immediately. However, it's not a normal return. For example, there is no return value. The only way to capture control from a method that is returning as a result of an exception being thrown, is to have an exception handler.

Can you throw an exception and return something?

It's not possible to both throw an exception and return a value from a single function call.

Why is using exceptions a better idea than returning an error value?

When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough. When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code.


2 Answers

unreachable code

I tend to denote it an error in their code. The statement is not reachable. Every static code anaylsis tool will complain about this unreachable statement. Even when it has no harm in this case you will get a load of warnings when checking your code. If you turn these warning type off you will perhaps miss other logic errors within your code. It's a real bad smell and it needs to be fixed.

like image 124
mdo Avatar answered Oct 20 '22 08:10

mdo


Because they made a mistake, or it's their personal preference. It's impossible to get to the return in that code, but there's no real harm in including it.

From the docs (emphasis mine):

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.

like image 33
nickb Avatar answered Oct 20 '22 09:10

nickb