?
Solved

Please explain this exception example

Posted on 2005-04-15
15
Medium Priority
?
269 Views
Last Modified: 2010-03-31
Experts,

I have these two scenarios, one compiles fine and the other does not. I am unable to figure out why. CustomException is just a class that extends java.lang.Exception.

public class ExceptionTest {
      public static void main(String args[]) throws CustomException{

            ExceptionTest m_test = new ExceptionTest();
            m_test.doTest();
      }
      
      public void testException() throws CustomException{            
            throw new CustomException();
      }
      
      public Vector doTest() throws CustomException{
            try{
                  testException();
            }catch(Exception e){
                  throw e;
            }
            finally{
                  return null;
            }
      }      
}

In the doTest method, I throw java.lang.Exception but do not need to declare that in my method. Declaring CustomException is sufficient. HOWEVER, when I change the doTest method to return void and remove the finally block, the compiler complains about declaring java.lang.Exception. Also, if I return a value from outside the finally block, I get the same compilation error.

Why is it that by simply specifying a return type and returning from the finally block, the compiler allows the code to be compiled? BTW, I am using IBM JDK 1.3, but I noticed this behavior from Sun JDK as well.
0
Comment
Question by:gvijay1
  • 7
  • 5
  • 3
15 Comments
 
LVL 92

Expert Comment

by:objects
ID: 13795821
Firstly if your method is throwing an exception, it should declare that it throws it.
0
 
LVL 92

Expert Comment

by:objects
ID: 13795832
The existance of the return in the finally block will result in the exception not actually getting thrown (by your method). That is why it compiles ok.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13795891
I think since 1.4.? Sun compiler will omit a warning when you have a return statement from a finally block.
This is a bad practise as it will mask both thrown Exception or pervious returned values.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 92

Expert Comment

by:objects
ID: 13795922
Your code is better structured like the following (though it won't compile because it does not declare that it can throw an Exception). So you also need to change the declararion to define that it may throw that Exception.


public class ExceptionTest {
     public static void main(String args[]) throws CustomException{

          ExceptionTest m_test = new ExceptionTest();
          m_test.doTest();
     }
     
     public void testException() throws CustomException{          
          throw new CustomException();
     }
     
     public Vector doTest() throws CustomException{  // <-- should be throws Exception
          Vector result = null;
          try{
               testException();
          }catch(Exception e){
               throw e;
          }
          finally{
              // add cleaup etc here, but don't return
          }
          return result;
     }    
}
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13795939
Also, if you know that testException throws CustomException why do you catch Exception?
Are you trying to catch also RuntimeException in that block?

If you change the code to:
   try{
               testException();
          }catch(CustomException e){
             // apply some logic here (like log otherwise there is no point of catching it)
              throw e;
          }

then you can leave doTest() throws CustomException instead of having throws Exception.
0
 
LVL 92

Expert Comment

by:objects
ID: 13795961
> Also, if you know that testException throws CustomException why do you catch Exception?

The example does not appear to be functional code, just a test to determine why the compiler was allowing it.
Which is because the exception does in fact not get thrown, so it doesn't need to declare that it does.
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13795991
objects, I realized that this is a test code to get better understanding on Java language.
I mentioned that to make a point clear as part of a "best practise" behaviour.
0
 

Author Comment

by:gvijay1
ID: 13796013
Objects,

You mentioned that the exception "does in fact not get thrown". I am not sure how the exception does not get throws just because I am returning the value from the finally block. The testException() method which is called actually throws the CustomException.

So, even after executing the finally block, doesn't the doTest method still throw the exception?
0
 
LVL 92

Expert Comment

by:objects
ID: 13796031
> even after executing the finally block, doesn't the doTest method still throw the exception?

no it doesn't, because you return from the finally block (which is executed after you throw the excepotion)
0
 

Author Comment

by:gvijay1
ID: 13796056
In my example, I have used a generic meaningless Exception. However, say an SQLException was throws by the JDBC driver - if I return a value from the finally block regardless of what it is, then the exception is ignored?

If this is true, would there be any practical reason to do the above?
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13796068
>> if I return a value from the finally block regardless of what it is, then the exception is ignored?
Right.

>> If this is true, would there be any practical reason to do the above?
No, see my comment about Java compiler warning.
0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 13796075
> if I return a value from the finally block regardless of what it is, then the exception is ignored?

correct

> If this is true, would there be any practical reason to do the above?

None, it fact returning from finally should be avoided
0
 
LVL 15

Expert Comment

by:aozarov
ID: 13796076
It is not only the exception that might be ingnored (when having return from finaly) it is also any previous returned value which will be ignored.
0
 
LVL 92

Expert Comment

by:objects
ID: 13796083
Issue arises because code in a finally block is guarnteed to be executed, so if you return inside it you lose any previously thrown exceptions or returns.
0
 

Author Comment

by:gvijay1
ID: 13797242
Thanks for the comments. It was very helpfull and informative.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question