Avoidance of the catch clause

I have a function that checks whether the user has made any changes, and if so, warns them about this fact. When they choose to discard their changes, I have another function that: a) restores the state for preliminary editing and b) updates the global object that contains information about the current editing (including whether it exists).

What I do not want is that when I try to delete the elements of the edit window, some error occurs, and as a result, the system does not update the flag of the global object or does not show hidden elements of preliminary editing. If this happens, the program might think that editing is still happening when it is not, leaving the user in the "Undo Changes" trap? cycle. For this reason, I will catch any errors that occurred during the destruction phase, and then show hidden elements and update global values, for example:

function cancelEdit() { try { // destroy editing boxes // [code goes here] } catch(e) { } finally { // restore hidden elements // [code goes here] // update global edit cache object // [code goes here] // rethrow the error for analysis server-side if(window.onerror) window.onerror(); } } 

Having an empty catch block like the one above seems like code smell to me, but I don't think this way is necessarily better. (But perhaps this is so.)

 function cancelEdit() { try { // destroy editing boxes // [code goes here] } catch(e) { cancelEditInternal(); // rethrow the error for analysis server-side throw e; } cancelEditInternal(); } function cancelEditInternal() { // restore hidden elements // [code goes here] // update global edit cache object // [code goes here] } 

Am I missing something? Is there a pattern that I neglect ... or is it just a consequence of the fact that I use try / catch / finally, where it is usually not used?

0
source share
2 answers

You can use the finally block:

 function cancelEdit() { try { // destroy editing boxes // [code goes here] } finally { cancelEditInternal(); } } 

The finally block will execute if the try body will try error. (If you save the catch clause, the finally block will still execute.)

+3
source

If you do not need a catch , then do not use it:

 try { // destroy editing boxes // [code goes here] } finally { // restore hidden elements // [code goes here] // update global edit cache object // [code goes here] // rethrow the error for analysis server-side if(window.onerror) window.onerror(); } 

As you can see in the specification , the try consists of a try , followed by either catch , or finally or both.

+2
source

All Articles