D
D
dev4002016-04-02 11:58:40
PHP
dev400, 2016-04-02 11:58:40

Why are exceptions needed?

There is such a situation

public function getNews($id) {

        $this->key = "id";
        if(!$rows = parent::findById($id)){
            throw new \Exception('not find news');
        }
        return $rows;

    }

If there is no news, an exception is thrown.
b0a9fa6173184e3b8684e675c97d54a6.png
So why not just do
public function getNews($id) {

        $this->key = "id";
        if(!$rows = parent::findById($id)){
            return "Нет новостей";
        }
        return $rows;

    }

Instead of porridge with an exception, we will see a beautiful message.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
crmMaster, 2016-04-02
@dev400

Instead of the expected array, you will get a string. The behavior of the function is undefined.
Exceptions can be handled by everything, such crap (sorry for the expressions, but you can’t call it in another way) - you can’t handle it in any way.
The exception has a backtrace, your solution does not - it becomes more difficult to track how, why and where this error came from.
Exceptions can be thrown anywhere, your approach requires throwing an error response to the controller, which is a gross violation of the principle of encapsulation.
In general, the question is very strange, juniors for such questions should have a preventive conversation about OOP and error handling, and for similar code they should be beaten on the hands with a stick.

T
trevoga_su, 2016-04-02
@trevoga_su

In this example, everything is wrong - it is most appropriate to return an empty array or an object that implements the Countable interface (provided that if news is found, they are also stored in this object).
No news is NOT an exception. The example is not 100% correct.
An exceptional situation - we cannot connect to the DBMS to get the news.
And exceptions are needed, You just don’t know how to cook them and don’t understand what it is. There is a lot of information on the Internet about exceptions. There is no point in explaining here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question