Hi,
Im using exceptions very seldom because im not sure when is a good moment to use it.
Of course in try catch construct but where outside try-catch do you throwing exceptions?
(Im asking about typical situations/cases)
There are many tutorials how to technically define, thhrow, handle exception but almost zero, about where they are very useful.
Could enyone advaice me when should I throw exceptions?
@bor1904 Exceptions are exactly that: something happening in your application that’s an exception to the norm. So if you have some business logic that can’t complete normally because of some circumstance, that’s when you would define and throw an exception, to indicate what the problem may be.
@martinbean unfortunatelly its obvious and I know that, but ... I always can do this by "if" statment and returning "false" value for example. If we "waiting" for some app "mistake" then why we shouldnt use specific return value as information about concrete fail?
One construct less -> easier, cleaner and so on
So why/where throwing exception onstead of return false -> if() ? :)
From how many levels deep in your application code will you be returning false until you get to the Http layer where you finally can return a response with an error message.
Exception handling means the exceptional behaviour happens; an Exception is thrown, and you can handle it (returning a response if you wish) rather than returning spurious values back up the stack.
@KBorowski Because what does “false” mean? Could mean anything. An exception class has a type and therefore conveys more information about what went wrong than “false”.
For example, a CardDeclinedException is much more helpful than some method just returning false.
Return values also have to be handled by calling code. Exceptions don’t. They’re raised and they stop code execution to the point they’re caught. If you’re using Laravel properly, then you’ll let its exception handler handle exceptions and convert them to an appropriate HTTP response.