Throwing exceptions and return types

When throwing a new exception, it is best to simply return true if you do not need to exclude any exception. An alternative is to return false instead of throwing an exception. Im using php.

+4
source share
2 answers

It all depends on what you do. Personally, I use them all the time, so I don’t need to check the return value (a silly but illustrative example):

function ArrayToObject(array $array) { $obj = new StdClass(); foreach ($array as $key => $value) { if (!is_string($key)) { throw new Exception('Expects only string keys in the array'); } $obj->$key = $value; } return $obj; } 

This way I can do:

 $array = array('foo' => 'bar'); try { echo ArrayToObject($array)->foo; //Prints "bar" } catch (Exception $e) { //Handle error here } 

This allows you not to worry about the error checking your results. You can handle errors directly in the catch block.

So no, don’t change what you are going to return based on exceptions ... Let exceptions handle errors and a modified workflow for you ...

A more realistic example (in pseudo-code):

 try { open database connection; send query to database; operate on results; } catch (DatabaseConnectionException $e) { handle failed connection here; } catch (DatabaseQueryException $e) { handle failed query here; } catch (Exception $e) { handle any other errors here; } 

Obviously, provided that your database functions / methods throw these exceptions ...

+13
source

It depends on the purpose of your function and the reason for the return. Use exceptions to return from a function during an error / unexpected condition. Use return values ​​for standard operations.

Similarly, do not use return values ​​for unforeseen situations. If your function will not return anything significant for reference to a null pointer, divide by zero, there is no data connection, you should throw an exception. First, it allows you to isolate the error handling code with a catch block. Secondly, it allows you to provide more information on why this happened, and not just a “lie”. It is very annoying when something fails, and all the information you receive is simply a “mistake”.

In addition, you do not want to throw exceptions as an alternative to flow control. You could get creative and write a comparison function that did nothing if it were equal, threw a GreaterThanException or LessThanException if it was not equal. But now you have lost the advantage of splitting error handling code (since the standard processing code is now contained in catch blocks along with the error code). Also, although I'm not sure about the performance of exception handling in many environments such as php, it is probably more expensive to create an exception object and do type comparisons for catch blocks, rather than just returning.

0
source

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


All Articles