• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception Handling(Checked/Unchecked)  RSS feed

 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,
I know that extending Exception class makes ur new Class as Checked exception, and extending RuntimeException makes ur new (exception)class as unchecked excpetion.
Moreover, extending Throwable class makes ur new class(exception) as checked exception. So my question is why it is so? I mean how java complier confirms which is unchecked and which is checked exception?
Is it checks something like if my new class(Exception) isinstanceof RuntimeException only then it is unchecked exception??
Thanks in advance...
Sandeep Jindal
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps you can find someone, who will translate your question to english.
I don't understand it.
 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something like, not only. Too isinstance of Error.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it checks something like if my new class(Exception) isinstanceof RuntimeException only then it is unchecked exception??

[ April 05, 2004: Message edited by: Jim Yingst ]
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Stefan,
I am rewriting my english question to english!!
My Question goes like this:::
MyException extends Exception {
}

MyException -> Checked Exception

MyException extends RunTimeException{
}
MyException -> Unchecked Exception

MyException extends Throwable{
}
MyException -> Checked Exception

So my question is what is the general method(mechanism) by which Java Compiler determines which one is Checked Exceoption and which is uncked Exception?
Thanks and Regards
Sandeep
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is what is the general method(mechanism) by which Java Compiler determines which one is Checked Exception and which is unchecked Exception?
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you write a class that extends Throwable, it is checked, but it is not an Exception. It's a Throwable. Just a point minor point.
The compiler determines whether your Throwable is checked or not with the following test:

Obviously this is not real code used by the compiler, but it represents the logic used to figure out whether to require callers to catch the Throwable or not.
sev
[ April 11, 2004: Message edited by: sever oon ]
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sever,
If this is the logic by which the compiler treats the exceptions, then i was thinking on rite track.
But i never knew bout this method
deleteAllDataFromHardDriveAndMeltMotherBoardIntoGooeyMess()
)
Thanks
 
Wael Aoudi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure i understand the whole exception thing as clearly as i thought i did. Your question completely switched the facts on me. I thought that Errors and RuntimeExceptions (and their subclasses are unchecked) but all other exceptions are checked. and you use the keyword Throw to throw an exception to another class and have it register it. While you extend the class Exception to have it propagate upwards. Am I right? If thats true how do you make an unchecked exception checked?
Thank you,
Wael Aoudi
SCJP
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An unchecked exception will always remain an unchecked exception.
You can however catch it just as you would a checked exception, no problem at all.
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yea...with checked exceptions, the compiler *requires* you to catch them. With unchecked, you are not required to catch them, but you can if you want to.
Of course, it's very rare circumstances when you would, or should, do such a thing. After all, how can you possibly know which unchecked exceptions can be thrown by a method? ...methods are not required to declare unchecked exceptions that they throw.
Unchecked exceptions are really not meant to be caught. Can you imagine writing code that catches NullPointerException? You'd have to catch it every time you called any method at all, because it can always be thrown anywhere at any time. The same is true, really, for all unchecked exceptions. If you find yourself catching these, then you should reconsider your design.
sev
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So we can also deduce that there is no benifit/good programming of extending runtime exception, i mean creating a custom unchecked exception, though we can do so, is it??
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an Exception is something way beyond your control (like a failed network connection or a database error resulting from the database being down) you make it a RuntimeException.
If it's something you can handle gracefully typically you'd make it a checked Exception.
As to catching RuntimeExceptions, I sometimes do it in order to handle them anyway and do some default handling instead.
For example, I have a database that will return an amount as a String. The runtime exception attempting to turn that into a double I catch and handle because I KNOW that there may be empty Strings instead of numbers if the value is supposed to be 0.00 (it's an old program that inserted the data and it had a tendency to insert empty strings or spaces instead of 0 for numbers and **/**/** for dates if those aren't filled).
In some other cases I might catch one RuntimeException and rethrow it as something else with additional data to make it clearer in our logs where exactly the error occurred and what the conditions were.
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Jeroen,
Thaks for your reply. But i have heard and in Sun's specifications also, i have read that one should not catch runtime exceptions. I mean, instead of putting a code block in try catch checking for runtime exception, one can always use if else keywords of java.
Like in your case also, if you are excepeted to get an empty string instead of a string with a doudle value, you can use some block like:
if(string == "" || string==null)
I know, that using these blocks we can check for every exception, for this holds true(i mean we should use if else) in case of runtime exception. Isn't it true?
Moreover, if a methods throws a runtime exception, the calling method need not catch/throw that exception.
So as per my knowledge, one can always avoid catching the runtime exceptions. Please correct me where i am wrong.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
true, you could do that. But more often than not I want to skip the record if I get a NumberFormatException. In those cases just catching it and continuing on to the next record is far easier than messing around with all kind of conditional blocks.
One should NEVER catch RuntimeException, but catching specific subclasses if you expect they may be thrown and you can meaningfully handle them is no problem (or repackage them in your own exception class and rethrow them as that which is another tactic I employ frequently).
The same is true for Exception. Any code that has "catch (Exception e)" in it needs refactoring IMO (same for code that has "throws Exception" which should throw a specific exception subclass instead).
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Jeroen,
Thats true, and i agree with you that in a few cases we can catch RuntimeException or sublclasses of it.
But your statement
or repackage them in your own exception class and rethrow them as that which is another tactic I employ frequently).

If i make my own exception which extends RunTimeException/Subclass of it, it will be another uncheked exception and throwing it will be again of no meaning, cause again the compiler will not force to catch that unckecked exception.
I explain it with the code


This is my question actually, whether there is any benifit of making our own unchecked exception!
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

We use a custom debug logger, and our own exceptions to wrap standard exceptions with more info.
Somewhere down the chain that Exception would cause an error message to be displayed to the user which is more meaningful than a stacktrace.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to throw gas on a fire, I'll mention there is a school of thought that says checked exceptions were a mistake and Java would be better off without them. Believers make all their own exceptions unchecked to clean up their method declarations and code. I tried this in one program that has quite a deep call stack, but can really only do something interesting about an exception at the highest level. None of my public methods declare any exceptions, but many throw custom unchecked exceptions. Any problem at any depth in the call stack bubbles back up to the highest level for simple, consistent handling. It worked great for me that once. Can't say about anybody else.
 
Sandeep Jindal
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Stan,
Your school of thoughts is amazing and sufficent to burn the fire with more pace. Can you explain how unchecked exception was a mistake in any case..
Yes, I understand the benifit of unchecked exception as said by Jeroen, but i did not get a very basic thing what is the benifit of following code as told by you !!
public someMethod throws someUnCheckedException{
}
Because, java compiler will never enforces us to catch any unchecked exception.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main advantage of declaring the unchecked exception in the method clause as being thrown is for clarity to people reading the code (and for Javadoc generators ).
It makes it clear that the exception can be thrown so you MAY handle it if you want to.
For example, check out the JavaDoc for the J2SDK and J2EE. Many methods will be listed as throwing for example NullPointerException (which is unchecked).
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And as to different schools, there are indeed many.
Apart from people advocating checked or unchecked exceptions, there's people saying you should handle all unchecked exceptions as well as people saying you should handle none.
Myself, I'm trying to be pragmatic about it.
I create most of my own exceptions unchecked, then tell in the method signature which I may throw.
Ignore that at your own risk or handle as you will. I don't care, but I do give you the option to do either as you please as well as (or so I try) a decent error message when you do get an exception so you may know what's going on (I'm experimenting with putting error codes on the front of these so on catching you can look up the code and decide in software what the true reason was, could be interesting for giving customised error messages to the end-user or substituting different error handling for different instances of the same exception class).
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you missed a word in there somewhere ...
None of my public methods declare any exceptions, but many throw custom unchecked exceptions.

The interfaces are very clean with NO exceptions declared. The exceptions that are thrown are NOT declared.
I've only used this style in one program where it was nicely suited to the structure of the program. Any time you catch an exception ask yourself what are you going to do that is better letting it bubble up? Log it and throw another? Yawn, why bother? In my case, I could not do anything useful in lower level code, so I just let exceptions fly. I did not need to know whether or not any type of exception might be thrown until I got up to the top level code, and I knew better than to let myThread.run throw anything so I caught em there.
To keep up my rule - public methods declare no exceptions - I did have to catch all exceptions declared by other people's code (the JDK) and throw my own unchecked ones. But only in public methods.
That other bit of advice - never catch unchecked exceptions - is great for many student projects and command-line utilities. If you're not really able to do anything useful in response to an exception, let it bubble up, kill the JVM and spew a stack trace on the console. I do that when I'm the customer and the stack trace will be of interest. But in a production Swing app that would be pretty unprofessional. And if you're locking external resources, it would be very bad manners.
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way I look at exceptions is this...when you write a method, you should specify a contract for that method, with preconditions and post-conditions. The preconditions specify what the caller must ensure about the state of the system before calling that method. If the caller meets all your preconditions (checks that the state of the system satisfies those requirements), then your method promises to meet the post-conditions you specify.
For some exceptional circumstances, even though the caller has met your specified preconditions for a particular method, you still cannot meet the promised post-conditions. In that case, you throw an exception to indicate that something has gone wrong that is out of both your and the caller's control. Should it be a checked exception or an unchecked exception?
That depends on what has gone wrong. If the situation that raised the exception has the system in an invalid, but possibly recoverable, state, then it would make sense to throw an exception back to the caller indicating the problem and let the caller decide if they can perform the recovery. If the system is in an inconsistent state that is not recoverable for the caller (and the caller's caller, and that method's caller, etc), then you throw an unchecked exception.
Examples might help. You are writing a method that takes a URL argument and tries to download the specified image. Preconditions: (1) the URL must not be null, (2) it must reference an image, not a web page or something else. If the caller meets these preconditions, you specify post-conditions: (1) the return value will be a byte[] containing the image, (2) getLastImage() on this object will return the image retrieved by the last call to this method.
Ok, so a caller comes along with a URL, does a null check, knows it references a valid image, etc, all the preconditions are met. Normally, your method would be able to meet the post-conditions, but it just so happens there is a lot of network traffic and you are not able to reach the server containing the image. You throw a checked exception back to the caller because this is situation can reasonably be recovered from--the caller can choose to wait a few seconds and try again, and it will probably work. The caller may decide to get the referred image from a cache because they don't necessarily care if it's changed since the cache was last updated. Whatever.
Another caller comes along and passes you a non-null URL that refers to a valid image. Again, your method should be able to meet the specified post-conditions. However, one of the things that your method does for some reason or another is that it goes and gets two numbers from a database and divides them (say it's keeping track of traffic statistics or something like that--these stats are absolutely required and not optional, and should therefore be specified as post-conditions as well--in addition to getting the image). In this particular case, though, the denominator supplied by the database is zero, and when you try to divide it throws an unchecked exception. But this is proper, because there's obviously an unrecoverable situation--some other part of the app at some earlier time, unrelated to what's going on at the moment, put that invalid zero in the DB. That part of the app contains a bug that allowed this invalid data into the DB, and there's not a darn thing you or the caller can do about it. So, you throw an unchecked exception because there's no way to recover.
Well...a small correction. For a particular case, you might be able to devise a scenario where the caller could recover this situation and continue on. But that missed the point, really--the question is, *should* the caller continue on processing, leaving the system hobbled and in this invalid state? The answer is no--when there's a bug roaming around the system, which there is because that denominator fetched from the DB should never have been put there in the first place, it is not acceptable to simply continue on processing and let the system further degrade. So even if you can continue on, you wouldn't want to--the only rational thing to do here is recognize that the system is broken and go and fix the bug.
So, to sum up, checked exceptions represent problems that occur as a normal part of the processing in an application...they are exceptional conditions that arise to make continuing on impossible even if all your code is perfect and bug-free.
Unchecked exceptions represent a problem with your code--things have entered an inconsistent state and even if processing could continue, it shouldn't, because the bug needs to be ferretted out and fixed, and this will not ever happen if the system just buries the problem and continues bumbling forward until things degenerate to an irreparable state.
Just for the sake of completeness, I might as well address errors. These happen when some hard limitation of the system has been exceeded and processing cannot continue because of an irrecoverable problem (again, read this as "a situation you wouldn't *want* to recover from even if you could", instead of "a situation that could possibly be recovered") having to do with the environment in which your program is running. In other words, something went wrong that has absolutely nothing to do with the logic in your program, and completely orthogonal to the problem domain over which you're operating. For instance, you ran out of memory. Or the hard disk filled up. Or the CPU overheated. Or your little sister just poured a half a pint of Aunt Jemima buttermilk pancake mix all over your motherboard.
sev
[ April 16, 2004: Message edited by: sever oon ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!