aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Catching non-thrown exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Catching non-thrown exceptions" Watch "Catching non-thrown exceptions" New topic
Author

Catching non-thrown exceptions

Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
Hi guys, consider the following code:



This code compiles fine. The question I have is, if we change the catch-block argument to look for an IOException instead of an Exception, it will fail with the following msg:

TestFin.java:7: exception java.io.IOException is never thrown in body of corresponding try statement
} catch (IOException e) {e.printStackTrace();}
^
1 error


Now what I am wondering is basically what the mechanic/reason is that the compiler reacts with an error for IOException, but not Exception. I can imagine it is because the compiler somehow checks if the exception is a checked exception. If that's the case, I'd appreciate some insight how exactly it checks for it. Exception is ofcourse higher in the hierarchy, ruling out the possibility that the check is made by an "instanceof RunTimeException" test, and therefor does not give an error. So how does this check work/function?

// Andreas
Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
Because System.exit() can throw a SecurityException, which can be implicitly down cast to an Exception. Nothing in the body of the try throws an IOException.

Cheers,
Shawn
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Shawn Smith wrote:Because System.exit() can throw a SecurityException, which can be implicitly down cast to an Exception. Nothing in the body of the try throws an IOException.


Hello Guys, @Shawn the above statement is NOT correct because with an EMPTY(without codes) try-catch block and an Exception as the catch argument the code still compiles, but when I changed it to known checked exceptions like; IOException, ParseException, InterruptedException etc including their corresponding imports, the code did NOT compile, I think Andreas ideas should be taken into consideration.


OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
Fair statement Ikpefua. The Sun documentation states that the creation of an exception handler begins by having a try block with "one or more legal lines of code that could throw an exception". Since an empty try block doesn't meet that criteria, and there is nothing illegal about having an empty try block, you have to catch something. The compiler can evaluate all possible throws clauses for valid code, but lacking that can only handle the ultimate base class (that requires catching).

Since you can't have a try without a catch, and you can have an empty try block, you must allow the system to catch something.

If you do have "one or more legal lines of code that could throw an exception", you can only catch either Exceptions declared in the throws clauses of those lines, or their base classes.

Cheers,
Shawn
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61658
    
  67

Shawn Smith wrote:Since you can't have a try without a catch ...

Incorrect. A try can most certainly be written without a catch. There must be one of a catch block or a finally block, but the catch is not required.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
Shawn Smith wrote:Since you can't have a try without a catch, and you can have an empty try block, you must allow the system to catch something.


Arguably.... the fact is you can have a try without a catch, if you use a finally, so I don't think what you're saying holds true.

It seems to be that it is always legal to catch RuntimeException, whether or not you invoke any code that might throw it. But if this is 100% true I don't know...

Shawn Smith wrote:If you do have "one or more legal lines of code that could throw an exception", you can only catch either Exceptions declared in the throws clauses of those lines, or their base classes.


I don't think this is the case. I think the following code shows that it's legal to catch things that cannot be thrown inside the try clause, which in this case only has a potential "IOException".



We can guess several things from this, like "its always possible to catch RuntimeException", and "Exception is the only exception to this rule because an Exception can potentially be a RuntimeException" and so on. But does anyone actually know what's going on here and why?

// Andreas
Boris Mechkov
Ranch Hand

Joined: May 13, 2011
Posts: 72

If you have an IOException for example and nothing that throws an IO exception, you get a compile error. A broad "Exception" can be caught for whatever reason (could be any kind of checked exception or even a programmer defined custom exception, even Runtime Exception), but a specific IOException (for example) is thrown by specific IO-based activities, defined in the Java API.

Another plausible explanation is that you can catch an "EXCEPTION" because the exception could be a Runtime exception that you want to handle. And since runtime exceptions are not checked they can be caught by just "catch (Exception e)"...


OCPJP 6
Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
We can guess several things from this, like "its always possible to catch RuntimeException", and "Exception is the only exception to this rule because an Exception can potentially be a RuntimeException" and so on. But does anyone actually know what's going on here and why?


I suppose this makes sense since since RuntimeExceptions aren't required to be declared in throws clauses, so the compiler wouldn't be aware of them in the same way as Exception.

I was aware of the finally clause and was only trying to imply that try's have to be handled, and if java (for reasons beyond my understanding) allows for empty try blocks, it has to to provide some kind of hook to handle it gracefully.

Though if any of my developers ever show up with



or



to a code review, in the words of Ricky Ricardo, they'll have some 'splainin' to do.

Thanks for the debate, you folks are going to make me think real hard before typing
Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
Let me try and clarify the questions of this thread.

1: Is it 100% true that you cannot try to catch ANY checked exception, unless you have invoked code that might throw it inside the try-clause?

2: Is it 100% true that you can always write code to catch any RuntimeException, whether or not you have invoked code that might throw it inside the try-clause?

3: Is there any other rule to this situation?

I'm pretty sure points 1 and 2 are true, but I'd like to have it confirmed. I also think that Throwable and Exception might be the only exceptions to these rules, since they can ofcourse always be a RuntimeException, but I'm just assuming here and you know what they say about assumption...

// Andreas
Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
Shawn Smith wrote:Thanks for the debate, you folks are going to make me think real hard before typing


Hehe, you're not alone bro, I always try and think twice before posting to make sure im not shooting my mouth off too fast

// Andreas
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Hello Guys, This debate is very interesting!...@Andreas It looks like the puzzle continues! Now observe how 'Exception' behaves in the following program:



Compilation FAILS at line 9 because the main method fails to comply with the decalre-or-handle obligation.
If you comment lines 3 and 9.....And uncomment lines 5 and 11 the code compiles and runs without problems.

Permit me add this question to yours: Why is 'Exception' behaving like 'non-checked' in a catch block and like
'checked' in a methods declaration?
For the purpose of the exam I think it is IMPORTANT to take note of this behaviour.

Shawn Smith wrote: Thanks for the debate, you folks are going to make me think real hard before typing


You are NOT alone bro, just like Andreas said, dont try to be perfect everyone here knows no one is above mistakes.
Andreas Svenkson
Ranch Hand

Joined: Jan 17, 2011
Posts: 179
Ikpefua Jacob-Obinyan wrote:Hello Guys, This debate is very interesting!...@Andreas It looks like the puzzle continues! Now observe how 'Exception' behaves in the following program:



Compilation FAILS at line 9 because the main method fails to comply with the decalre-or-handle obligation.
If you comment lines 3 and 9.....And uncomment lines 5 and 11 the code compiles and runs without problems.

Permit me add this question to yours: Why is 'Exception' behaving like 'non-checked' in a catch block and like
'checked' in a methods declaration?
For the purpose of the exam I think it is IMPORTANT to take note of this behaviour.

Shawn Smith wrote: Thanks for the debate, you folks are going to make me think real hard before typing


You are NOT alone bro, just like Andreas said, dont try to be perfect everyone here knows no one is above mistakes.


Interesting... My guess would be that the reason is fundamentally the same here, being that an Exception can be either a RuntimeException or a checked exception.

In my original question, we are always allowed to catch Exception and/or Throwable inside a catch-clause, even if, as far as we know, we haven't executed any code that throws them, due to the fact that they might possibly be a RuntimeException.

In this case, we are instead never allowed to let an Exception/Throwable go unhandled/undeclared for the very same, but reversed, reason: that they might possibly be a checked exception.

This is all my best-guess-reasoning though, if someone can confirm or explain it to be wrong, it is ofcourse appreciated.

// Andreas
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206
Ikpefua Jacob-Obinyan wrote:Hello Guys, This debate is very interesting!...@Andreas It looks like the puzzle continues! Now observe how 'Exception' behaves in the following program:




Permit me add this question to yours: Why is 'Exception' behaving like 'non-checked' in a catch block and like
'checked' in a methods declaration?
For the purpose of the exam I think it is IMPORTANT to take note of this behaviour.



If you go back to K&B Chapter 5 on exception and reread through you'll understand why. The fact is that RunTimeException or Uncheck Exception doesn't need to caught in try/catch block, the compiler doesn't care. It doesn't matter if you declared or handle the compiler won't give you a COMPILE ERROR like Checked Exception does if you don't declare or handle.

Note: The compiler doesn't ENFORCE the handle or declare RULES on the Unchecked or RunTimeException just like Error. Therefore, lines 5 & 11 compile without any problem vs lines 3 & 9.


----------

Consider this similar problem:




What line do you see the problem and how do fix and make it compile?





OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Hello Tommy,
thanks for your participation, I understand PERFECTLY everything you have explained, however you seem NOT to understand my question...So let me repeat it:

Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER and like 'checked' when used in a 'methods' DECLARATION?

P.S:In your code the problem is line 7. (I must admit that it is DIFICULT to spot) because the class Airjet has an implicitly placed default constructor that fails to comply with the obligation of handle-or-declare, this is how the class really looks 'behind-the-scenes':




Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206
Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER and like 'checked' when used in a 'methods' DECLARATION?


@Ikpefua

Really I'm not quite fully understand your question, but I can address it based on what you asking.

I'm not quite sure what do you meant by "catch Parameter", but I think you referring to the try/catch clause. If so, the rule is if the calling method declared a Checked Exception then the caller of the calling method have to handle with try/catch block otherwise it will throws a COMPILE ERROR. However, you can DUCKING the Exception to the method the caller is in by declared or throws an Exception (i.e main()).

To make it clearly of what I meant see code before for illustration:



To answer to your question "Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER", the fact it's NOT behave like unchecked exception simply because you didn't throw any Exception in go() method body therefore, when you invoke the method go() it just execute straight through because it found no Exception.

And "like 'checked' when used in a 'methods' DECLARATION", well the RULE is when you calling a method that declared an Exception you must provide a try/catch clause or Ducking the Exception. If you don't fulfill any of the those requirement the Compiler will complaints and throws a compiler error.


If you want to see the code behave like checked exception then try to throw an an Exception in the go() method.

Let put in coding and see if that make sense:





Hope I've addressed your question, if not be more specific so, I can address more.

Here is a little recap from K&B book: Suppose your method doesn't directly throw an exception, but calls a method that
does. You can choose not to handle the exception yourself and instead just declare it, as though it were your method that
actually throws the exception. If you do declare the exception that your method might get from another method, and you don't
provide a try/catch for it, then the method will propagate back to the method that called your method, and either be caught
there or continue on to be handled by a method further down the stack.


--------------------------
P.S:In your code the problem is line 7. (I must admit that it is DIFICULT to spot) because the class Airjet has an implicitly placed default constructor that fails to comply with the obligation of handle-or-declare, this is how the class really looks 'behind-the-scenes':




Very good, you spotted the problem and I think you know how to fix it by now.

NOTE: Try some examples of Exception in method overriding and polymorphism, you'll encounter some of those on the Exam.

S Thiyanesh
Ranch Hand

Joined: Mar 19, 2006
Posts: 142
The reason that "Exception" is allowed in the catch clause is "Any runtime exception is a subclass Exception" and we are handling the broader exception.
We are not allowed to catch "IOException" if none of the enclosing code block can cause "IOException", since no RuntimeException is subclass of the "IOException".

Thanks,
Thiyaneshwaran S
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Hello Tommy,
thank very much for your time taken explanation...Im afraid you still dont understand my question, however your effort to explain is sincerely appreciated. I know 'practically' everything that my knowledge could be tested on about exceptions in the exams. I want to use codes to ask you the question so you can finally understand what I mean.

Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER // and like 'checked' when used in a 'methods' DECLARATION?

Now lets divide this question into two using small programs to demonstrate observe CAREFULLY:

1.Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER?



Since 'Exception' is 'Checked' why did the compiler NOT complain?
Since 'IOException' is also 'Checked' why did the compiler complain?

And be informed that all other 'Checked' exceptions do NOT compile
in this scenario.
_____________________________________________________________________________

2.and like 'checked' when used in a 'methods' DECLARATION?



Summary:

1. 'Exception' is NOT 'checked' in a 'catch' PARAMETER
2. 'Exception' IS 'checked' in a methods DECLARATION

Why???
Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

S Thiyanesh wrote:The reason that "Exception" is allowed in the catch clause is "Any runtime exception is a subclass Exception" and we are handling the broader exception.

Hello Thiyanesh...I understand better now, it means the compiler is aware that if there's any runtime 'checked' exception, it will ALWAYS be a subclass of 'Exception'.

However in a methods DECLARATION the scenario is different, we are saying in effect: "a 'checked' exception will be thrown", therefore an invocation of the method is 'compromised' to 'handle-or-declare'.

I hope my analysis is correct...Can you please confirm that? I will appreciate.

Regards

Ikpefua.
Shawn Smith
Ranch Hand

Joined: Feb 22, 2011
Posts: 41
The below is from the jvms (http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#3129). It almost seems to imply that the examples illustrated shouldn't compile, but maybe someone else can correct my interpretation. The other thing I found interesting was that the JRE does nothing to enforce the rule, so through some devious bytecode manipulation you could probably do some funky stuff.

A method should throw an exception only if at least one of the following three criteria is met:

* The exception is an instance of RuntimeException or one of its subclasses.

* The exception is an instance of Error or one of its subclasses.

* The exception is an instance of one of the exception classes specified in the exception_index_table just described, or one of their subclasses.

These requirements are not enforced in the Java virtual machine; they are enforced only at compile time.


To try to do a deeper dive I've been playing around with javap. In the VM spec there's an example of what's generated through a piece of code with try/catch block that looks like

Compilation of try-catch constructs is straightforward. For example,

void catchOne() {
try {
tryItOut();
} catch (TestExc e) {
handleExc(e);
}
}

is compiled as

Method void catchOne()
0 aload_0 // Beginning of try block
1 invokevirtual #6 // Method Example.tryItOut()V
4 return // End of try block; normal return
5 astore_1 // Store thrown value in local variable 1
6 aload_0 // Push this
7 aload_1 // Push thrown value
8 invokevirtual #5 // Invoke handler method:
// Example.handleExc(LTestExc;)V
11 return // Return after handling TestExc
Exception table:
From To Target Type
0 4 5 Class TestExc


With the empty try/catch in a main method, I get something like





Which makes it look like the compiler is just optimizing the exception out and ignoring it completely. In order to confirm what I was seeing I threw in something that has a legitimate throw



Which results in:



Line 16 and 17 show that the exception is recognized and has the handle set up.

I don't know if this answers any questions, but hopefully it's some useful additional information.

Cheers,
Shawn
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206

Your Question: 2.and like 'checked' when used in a 'methods' DECLARATION?

Regards to this problem I've provided the reason why it give you a COMPILATION FAIL. I
think you MISUNDERSTOOD the concept of exception being declared in methods and handle in
try/catch block. Correct me if I'm wrong...

Again, the RULE is when you calling a method that declared an Exception you must provide a
try/catch clause or Ducking the Exception. If you don't fulfill any of the those requirement
the Compiler will complaints and throws a compiler error.

Let's put in coding and see if it makes sense:







//-------------------------------


Your Question: 1.Why is 'Exception' behaving like 'non-checked' when used in a 'catch' PARAMETER?

Check out: In K&B book check out topic "Handling an Entire Class Hierarchy of Exceptions" for more info



Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Tommy wrote: Regards to this problem I've provided the reason why it give you a COMPILATION FAIL. I think you MISUNDERSTOOD the concept of exception being declared in methods and handle in try/catch block. Correct me if I'm wrong...


Hello Tommy,
again I want to express my appreciation for your effort in explaining these concepts, however if you NOTICED the last statement/s I made you will see that I agree with you and understand the concepts very well.

I was ONLY wondering why one is NOT 'obliged' to provide code that may result in an exception being thrown, when 'Exception' is used in a 'catch' PARAMETER, and in effect 'obliged' to handle-or-declare by a methods CALLER when 'Exception' is added to a methods declaration.

I know everything that is REQUIRED about exception for the purpose of the exams AND I understand these concepts better THANKS to you all.

Regards

Ikpefua.
Tommy Delson
Ranch Hand

Joined: Apr 13, 2011
Posts: 206
Ikpefua Jacob-Obinyan wrote:

Hello Tommy,
again I want to express my appreciation for your effort in explaining these concepts, however if you NOTICED the last statement/s I made you will see that I agree with you and understand the concepts very well.

I was ONLY wondering why one is NOT 'obliged' to provide code that may result in an exception being thrown, when 'Exception' is used in a 'catch' PARAMETER, and in effect 'obliged' to handle-or-declare by a methods CALLER when 'Exception' is added to a methods declaration.

I know everything that is REQUIRED about exception for the purpose of the exams AND I understand these concepts better THANKS to you all.

Regards

Ikpefua.


You're welcome....I see your POINT, but I need to consult with Oracle/Sun and those invented Java for insight why they allowed such things happen. I'm sure there are reasons behind that. Probably we need to dig more in the documentation to find out or check out with Oracle/Sun for the WONDERING.

Peace...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Catching non-thrown exceptions