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 return
ing 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.
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?
What is $sv1
? Is it actually the most explicit name you could give to the variable in a context of your business domain?
Why do you catch (Exception $ex)
instead of catching a more specific type of exception?
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
?
In $for_boolean = explode('boolean_', $column_name);
, what if the column name doesn't contain boolean_
?
Before doing $for_boolean[1]
, you don't check that you actually have at least two elements.
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).