0

This question already has an answer here:

I want to confirm the right approach of using try-catch exception handler.

I have written a query in a try block, and if any exception is thrown, it will execute a query in a catch block.

Is this the right way?

try {
    $query->fieldOrderBy($column_name, 'value', $sv1);
} catch (Exception $ex) {
    if (!empty($ex)) {
        $for_boolean = explode('boolean_', $column_name);
        $query->fieldOrderBy($for_boolean[1], 'value', $sv1);
    }

marked as duplicate by Arseni Mourzenko, gnat, user40980, user22815, durron597 Oct 21 '15 at 14:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

Can I execute a query in a catch block of try-catch?

You can do (practically) whatever you want in a catch block. There is some ambiguity when returning from within catch/finally, but this is not the case here.

Is this the right way?

It depends on what are you trying to achieve. If when studying the business rules it makes sense to execute a given database query when something goes wrong in a specific case, then yes, this is the right way. For instance, one could imagine a case where an element is added to a database and if it fails because of an unique constraint, tries adding the same element after changing the problematic value.

In your case, it might make sense to order some data by something, if it fails, order by something else, and if it still fails, propagate the exception up the stack. Without any information about the domain, we couldn't possibly guess whether your approach is right or wrong.

Your code, on the other hand, looks problematic.

  1. Given the name of $query->fieldOrderBy, I expect it to return something: either the ordered items, or the number of affected rows. You don't use/check the return value. Why?

  2. What is $sv1? Is it actually the most explicit name you could give to the variable in a context of your business domain?

  3. Why do you catch (Exception $ex) instead of catching a more specific type of exception?

  4. Why if (!empty($ex))? What are you trying to achieve? What would be the case where catch block will be executed, but the condition will result in false?

  5. In $for_boolean = explode('boolean_', $column_name);, what if the column name doesn't contain boolean_?

  6. Before doing $for_boolean[1], you don't check that you actually have at least two elements.

  7. If you're dealing with an SQL database, you shouldn't specify the names of columns in variables: this will result in computed queries, which will ultimately lead to SQL Injection (and poor performance).

  • thanks a ton. I jss need to confirm whether one can execute query in cache block or not. Thanks.I got my answer. – Sugandh Khanna Oct 20 '15 at 10:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.