Operation Status and Exceptions

I am curious when job status and exceptions are used. Say I have a TextProcessor class with getText() , processText() and sendText() . All these methods perform operations on the private data of the class. I need to make sure that all operations go smoothly. I have two options: each method can return the status of the operation (0 - success,> 0 error codes) or throw an exception inside the method. It seems that exceptions are a more convenient way to control the execution of the method, because I will need to do the following when the work statuses are returned:

 $result = textProcessor->getText(); if ( $result !== 0 ) { return $result; } $result = textProcessor->processText(); if ( $result !== 0 ) { return $result; } $result = textProcessor->sendText(); if ( $result !== 0 ) { return $result; } 

or in this way

 if ( textProcessor->getText() !== 0 && textProcessor->processText() !== 0 && textProcessor->sendText() !== 0 ) { return processingErrors::textProcessorError; } 

It all seems a lot simpler with exceptions:

 try { textProcessor->getText(); textProcessor->processText(); textProcessor->sendText(); } catch (textProcessorException $e) { return $e->getMessage(); } 

1) So what is better to use in my situation - operation statuses or exceptions?
2) In general, when do I use job statuses (return codes) and with exceptions?

+4
source share
1 answer

Exceptions are best used when some operation requirements are unexpectedly missing. For example, I expect that I can connect to the database. If I cannot, I cannot maintain the application even in a degraded state. I am raising an exception because I cannot go on. If I could continue, it could be something that I am registering, but not throwing an exception for.

However, for me this use is entirely for me. Having all the return codes you describe seems less optimal and not as readable as the exception option. When code is not readable, it is not so easily supported.

+1
source

Source: https://habr.com/ru/post/1502971/


All Articles