aspose file tools*
The moose likes Java in General and the fly likes Exception class is special? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exception class is special?" Watch "Exception class is special?" New topic
Author

Exception class is special?

Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
The Exception class itself is a checked exception (as anything not in the RuntimeException hierarchy should be). That's fine, but if I create a subclass of Exception, call it NewException, and then I use it with an empty try block:



compilation fails with "exception NewException is never thrown in body of corresponding try statement". But if I use Exception itself:



it compiles fine. Why is the behavior different between these two checked exceptions?

Thanks,
jdmaddison
Alain Boucher
Ranch Hand

Joined: Feb 25, 2003
Posts: 51
Hello... good question here.

Don't look for a java solution... it's a Compiler issue. The Compiler look if the exception is the class java.lang.Exception... create yourself a java.lang package, create a Exception Class that extends Throwable, like the original, then use this Exception... it will work...


Alain Boucher<br />Spare-Brain Consultants Inc.<br />SCJ2P,SCWCD,
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Alain's answer is a bit... cryptic. Maybe I can clarify a little.

The Java compiler warns about catch blocks that couldn't possibly be entered. Note that RuntimeException is a subclass of Exception, and there are a large number of RuntimeExceptions that can be thrown by virtually any code -- NullPointerException, ArrayIndexOutOfBoundsException, etc. Therefore a catch for Exception is almost always applicable.

Now, it's true, actually, that the compiler cheats a little; I'm pretty sure an empty try block can't throw an Exception (it can throw a Throwable, though: ThreadDeath is just one example.) The Java Language Spec doesn't seem to say anything about this (Jim, you listening?) But in any case, the catch block for Exception can catch the whole family of RuntimeExceptions, which needn't be declared, and therefore, in theory, can be thrown by any code.


[Jess in Action][AskingGoodQuestions]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[EFH]: The Java Language Spec doesn't seem to say anything about this (Jim, you listening?)

I think it does say something - it says the compiler is in error here. The relevant section is JLS2 14.20:

"A catch block C is reachable iff [...] some expression or throw statement in the try block is reachable and can throw an exception whose type is assignable to the parameter of the catch clause C."

The same text is found in the JLS3 beta, section 14.21.

It seems that in order for a catch block to be reachable, the try block must have at least one expression or throws statement. Thus the catch blocks in both of Joseph's examples is by definition unreachable, and the compiler is required report a compile-time exception here. Since it doesn't (in the second case, anyway) I would say that the compiler does in fact violate the spec here. Unless I've missed something somewhere of course...

This does not seem to be terribly significant for any practical application, since there's really no use that I can see for ever having an empty try block anyway. It probably would've been better if they'd just considered an empty try block (or finally block) to be a compile-time error. I suppose JLS3 is still in development; maybe one of us should report this earth-shattering news to them so they can fix it.
[ January 13, 2005: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Might a catchblock be reachable if the try itself (rather than something inside the try block) causes an exception to be thrown (is that even possible, I guess it may throw something)?


42
Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
As much as I'd like to claim credit for catching something as interesting and esoteric as this, I regret to say that a questions on one of Sun's mock exams has two extremely similar questions... with different answers, depending on this difference in behavior.

It's discouraging that even if it were possible for me to memorize the Java Language spec, word for word (yeah, right) and my two Cert Guides (in my copious free time, I'm sure), I could still get questions wrong where the only way to figure it out, is to actually compile and run it.

Thanks for your help,
jdmaddison
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Can you point out where these questions are?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Jim Yingst:
I would say that the compiler does in fact violate the spec here. Unless I've missed something somewhere of course...[/QB]


When you put it that way, I agree with you. I wonder, though, because I just tried this with Jikes 1.21 in "+P pedantic" mode (which is awfully picky,) and Jikes had no complaints. The Jikes folks, at least early on, were real sticklers for spec compliance.
Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
These questions are on the Sun practice exam - the first test:

WGS-PREX-J035C: ePractice Certification Exam for the Sun Certified Programmer for the Java 2 Platform 1.4 (180 day subscription) Exam

* WGS-PREX-J035B-Form1: Sun Certified Programmer for the Java 2 Platform 1.4

Thanks,

jdmaddison
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Joseph: so, I guess those exams are available only to those who pay for them? Or is there a public (legal) link somewhere? Assuming there's not - in the questions you saw, was there anything inside the try block? In general, the expected behavior is that you can put a catch Exception or catch Throwable just about anywhere, because almost any code could conceivably throw a RuntimeException or Error. The exceptions to this rule are very rare and unimportant, in my opinion, and it's unlikely you'll be tested on them. I'd alos note that real exam questions are put through a more rigorous review process than sample questions are, so I think there's a fairly low chance you'll see a question on the real exam where the answer is in disagreement with either your JDK or the JLS. (Any topic where the JDK does not obey the appropriate specifications is a bad thing to test on, after all.)

EFH: Interested to know that about jikes. Yes, jikes has tended to adhere very closely to the specs (and this particular spec doesn't seem to have chnaged lately), so there may indeed be some other point which I am missing here. No luck finding it so far though.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

OK, now I'm really curious. I compiled an empty try block with both javac and jikes, and both optimized the try block away completely -- i.e., there's no exception table entry for that try block (as shown by javap), and they don't generate code for any statements in the catch block. Surely there has to be some justification for this special case!
Joseph Maddison
Ranch Hand

Joined: Nov 04, 2004
Posts: 53
The example that used Exception, and which was legal, had a call to an empty method and then a System.out.println with a String literal inside the try block.

The example that failed to compile, used a new subclass of Exception and only had a System.out.println with a String literal in the try block, so my expectation was that they'd behave the same way, since they were both checked Exceptions... except that "Exception" is special...

jdmaddison
saran sadaiyappan
Ranch Hand

Joined: Dec 23, 2004
Posts: 39
Hi mates,
Already we have a lot of rep poseted....But I ll try to make it clear in one sentence.....If u try to catch a runtime Exception(which is infact not needed) which u never encounter in a code then it ll not throw compile time error.But if u try to catch any exceptions like SQLException(non runtime exceptions)it ll say "Exception is never thrown in the corresponding try statement."
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Joseph Maddison said:
The Exception class itself is a checked exception


From jls 11.5:
The subclasses of Exception other than RuntimeException are all checked exception classes.

Clearly, no Java class can be its own subclass, because then it would be its own superclass and a class cannot have two superclasses. Since Exception is not a subclass of Exception, it is not a checked exception.

I think the compiler logic is that it does not verify that a catch block for an unchecked exception is reachable. It might seem more logical to make a special case of an empty try block, but I don't see this as a compiler error. That would be ignoring asynchronous exceptions that can be thrown in an empty try block.

Normally, asynchronous exceptions are subclasses of Error, but to make a rule that empty try blocks can be followed by catch clauses for Error but not by catch clauses for Exception would make the compiler a bit too API dependent for my taste. I was looking for asynchronous exceptions under Exception and found TimeoutException in the 1.5 API. I'm not sure if I'm correct, but my point is that the compiler should not be any more dependent on the class libraries than necessary.
[ January 18, 2005: Message edited by: Mike Gershman ]

Mike Gershman
SCJP 1.4, SCWCD in process
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Mike]:

From jls 11.5:
The subclasses of Exception other than RuntimeException are all checked exception classes
Clearly, no Java class can be its own subclass, because then it would be its own superclass and a class cannot have two superclasses. Since Exception is not a subclass of Exception, it is not a checked exception.


The statement you quoted doesn't say anything about Exception (or Throwable) one way or another - it's incomplete. A full definition of checked and unchecked exceptions was found back in JSL 11.2:
The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes.

Exception (that is, a "true" Exception, not a subclass) is checked, definitely. Same for Throwable. Unfortunately this is a place where the "is a" concept of inheritance breaks down. An Exception is a checked exception, and a RuntimeException "is an" Exception -- but a RuntimeException is not a checked exception.
[ January 19, 2005: Message edited by: Jim Yingst ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Just a thought:

In an empty try block, isn't there, at least conceptually, an empty statement? Can an empty statement, theoretically, throw an exception?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jim Yingst:
An Exception is a checked exception, and a RuntimeException "is an" Exception -- but a RuntimeException is not a checked exception.


Well, yes - but "is a" is just a heuristic, anyway.

More important is Liskov's Substitution Principle. Is it violated here? I'm not sure, but I currently can't think of a possible violation...
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
In an empty try block, isn't there, at least conceptually, an empty statement?

In the JLS, an empty statement would have the ";" at least.

Can an empty statement, theoretically, throw an exception?

Well, if we did indeed have an empty statement, it seems to me it could throw an asynchronous error (which is limited to ThreadDeath or VirtualMachineError), but I can't see a justification for it throwing any RuntimeException. According to the JLS: "These exceptions are not thrown at an arbitrary point in the program, but rather at a point where they are specified as a possible result of an expression evaluation or statement execution."

Hmmm, on another look here: "Execution of an empty statement always completes normally." From that, not even a asynchronous exception is possible here.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Well, it was just a callow idea... Now I'm at a loss, too.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception class is special?