Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactor Exception Handling

Ok i have sinned, i wrote too much code like this

try {
   // my code
} catch (Exception ex) {
   // doesn't matter
}

Now i'm going to cleanup/refactor this.

I'm using NB 6.7 and code completion works fine on first writing, adding all Exception types, etc. Once i have done the above code NB do not give more help.

Do you know a way to say NB look again for all Exception types and make the proposal for handling them and do code completion again ?

like image 366
PeterMmm Avatar asked Jan 15 '10 10:01

PeterMmm


People also ask

How do you replace a try catch?

If your code snippet is taken from your real code as-is, only two situations are possible: (1) the exception never happens, or (2) the exception always happens. If (1) is the case, replace try/catch with the content of try block; if (2) is the case, replace try/catch with the content of catch block.

Why is Java exception a better alternative of returning error codes?

The biggest benefit exception handling has over error codes is that it changes the flow of execution, which is important for two reasons. When an exception occurs, the application is no longer following it's 'normal' execution path.

What is meant by error code and exception?

Error codes mean that you must carefully look at function calls to see if the programmer handled the possible errors. Exceptions mean that you must imagine what happens if an exception is thrown anywhere in the flow.


2 Answers

PMD identifies all these places where you have empty catch blocks (PMD does much more actually). It has NetBeans integration, so give it a try.

After identifying all the places with empty catch blocks you will have to consider each one by itself:

  • sometimes just log the message
  • sometimes restructure nearby code. I.e. if you are catching a NullPointerException, add a null check instead.
  • sometimes you will have to consider rethrowing (and declaring checked) exceptions.
like image 146
Bozho Avatar answered Oct 29 '22 15:10

Bozho


The problem is, that your catch-all handler "handles" all the exceptions, so there's not need for Netbeans to show any more hints.

If your exception handlers are already empty and you are planning to refactor them anyway, you can just temporarily remove them.

Tip: Auto-format your code, search for try and use bracket highlighting to find the matching catch blocks. Then remove all the handling code.

After that Netbeans will again propose various actions to handle the possible exceptions.

PS: Be careful, the default handling of Netbeans (i.e. just logging) is not always the best choice, either.

like image 23
Daniel Rikowski Avatar answered Oct 29 '22 15:10

Daniel Rikowski