Here's a Java nuance. If your method returns a value, a return statement must be guarenteed execution. You can prevent the execution of a return statement by accidently including it in a try-catch-finally block:
public boolean myMethod() { try { // Do some work return true; } catch (Exception e) { } }
In the above example it's pretty obvious that if the work of the method before the return statement generates an exception, the return statement will not be executed. The compiler will tell you that your method must return a value of type boolean. So, you might think you can move the return statement to the finally block since the finally block is always executed. You might write something like this:
public boolean myMethod() { boolean value = false;
try { // Do some work } catch (Exception e) { } finally { return value; } }
When you try to compile this code, you will find that the compiler is giving you the same error! The problem is that if there is an exception that happens as part of the finally block, the execution of the return statement might still be circumvented!!
Not good. So, what's the right way? Either move the return statement outside of the try-catch-finally blocks altogether, or return one value inside the try block before the first catch, and return a different value outside the try-catch-finally blocks. The latter may be the more common and preferable situation since it allows you to return a "good" value if there are no errors inside the try block and if there are errors, you can return a "bad" value outside the try-catch-finally blocks. Here's an example:
public MyClass myMethod() { MyClass obj = new MyClass();
try { // Do some work
// Return good value because there // were no errors. return obj; } catch (Exception e) { // Exception handling code } finally { // Clean up after errors }
return null; }
As you can see, making sure your method returns a value if it says it will can be a bit confusing. However, like most programming problems, if you understand the language and think through it logically, you can find solutions that make sense given your needs.
11:47:56 AM
|