When is it best to use exceptions in PHP?

I usually point out an error in the method when returning false, but it is not always gel with me semantically (since depending on the method it falsemay be a valid return).

I studied exceptions, and I wonder if they are one-time solutions? Should I return falsewhere I can still?

I may have completely missed the point here, so please bear with me.

// My old way
function getProductById($id) {

    if ( ! is_numeric($id)) {
         return false;     
    }

}

// My consideration
function getProductById($id) {

    if ( ! is_numeric($id)) {
         throw new Exception('The id must be numerical!');     
    }

}
+3
source share
4 answers

The exceptions are great! Let you save the error handling code from the error code.

, false . , - .

, ,

try {    
    func1($a);  
    func2($b);  
    func3($c);  
} catch (Exception $e) {  
    // error handling here  
}  

.

+1

:

, , .

, getProductById() , , , .

- " " " ". , , , , undefined/ .

false null, , ( ), .

P.S.: , . , , , , .

+2

, , , false , .

, , PHP ( , ). : , Product::getById($id). , , , . , . . :

  • ( Product::getByIdWithoutException())
  • (Product::getAllIds(array $ids)). , ( ..).

, , , , , . true , , , . , , :

function getById($id, $throwException = true) {
    if (!self::idExists($id)) {
        if ($throwException) {
            throw new IdNotFoundException();
        } else {
            return NULL;
        }
    }
    return self::getByWhereClause('id = ' . self::escape($id), $throwException);
}

, .

0

, .

, , , PHP , , .

, - , , , .

, , ? , , , , , .

, , , - , , , , . , , , , .

, , . -, , . , - , , .

, , , , , , .

0

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


All Articles