• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on Exception  RSS feed

 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,
Consider the following segment of code

class BadObjectException extends Exception {}
class BadIndexException extends IndexOutOfBoundsException {}

now is BadObjectException a checked exception or unchecked exception and is BadIndexException a checked or unchecked exception.

Thanks & Regards,
Sandeep
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JLS (Java Language Specification) 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.


Hence, the exception extending from Exception is a checked exception and the exception extending IndexOutOfBoundsException is not.

Regards,
Edwin Dalorzo
[ January 16, 2006: Message edited by: Edwin Dalorzo ]
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Edwin,

Thanks for your reply.
But I am still a little foxed.
Consider the following program


import java.io.*;
public class CheckException
{
public static void main(String[] args)
{
System.out.println("Hello World!");
try
{
temp();
}
catch (Exception e)//Consider This
{
}
}

static void temp()
{
}
}

This program compiles without any error.
However if the statement marded //Consider This
is changed to catch an IOException, I get a compile time error. Can you please explain this.

Cheers,
Sandeep
 
Gagan Deep
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep

Whenever we give any class name in catch(), compiler checks whether the code inside try can throw specified or any subclass of that class. If it can throw then it compiles fine otherwise compiler complains saying "code can never through this exception" or any similar error.

So when you are giving 'Exception' class in catch() it compiles because Runtime excpetions are subclasses of Exception class. So compiler can expect any runtime exception.

But if you specify IOException, then compiler checks code & finds code in try block can't throw this error & complains.

I hope this will help.

Thanks
Gagan.
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Gagan,

I was also under the same impression as you. But when I read the JLS posted by Edwin which says

"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."

, I got confused.

I request you to read the entire message and let me know if I am analyzing
in the wrong direction.

Thanks,
Sandeep
 
Enrique Villamizar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java.lang.Throwable class is the parent class for all objects can be thrown and caught an exception. Anyway you should use one of the subclass exceptions to describe any particular exception. There are three very important subclasses of Throwable:
1. Error class: that indicates a severe problem and represents unchecked exceptions (VirtualMachineError, AssertionError,..)
2. The Exception class is the base class for checked and unchecked exceptions(e.g. subclass IOException - checked - , subclass RuntimeException - unchecked -). Therefore I don't understand why Edwin said that
Hence, the exception extending from Exception is a checked exception...
I think that exception extending from Exception is a checked exception if it's not a RuntimeException.
3. RuntimeException is a subclass of Exception and it indicates conditions that should never happen if the program is correctly designed. RuntimeException is the base class for unchecked exceptions that might arise as a result of program bugs (in other words, unchecked exceptions are programer's reponsability).

To sum up (As Edwin said ):
A checked exception is every Throwable object which is neither an Error nor a RuntimeException. The compiler checks that your program handles checked exceptions but not unchecked exceptions.

Thanks a lot and looking forward for your comments,

Enrique Villamizar
(P.S. English isn't my first language).

[ January 16, 2006: Message edited by: Enrique Villamizar ]
[ January 16, 2006: Message edited by: Enrique Villamizar ]
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried doing a bit of research.
Consider the following program

import java.io.*;
class MyException extends Exception
{
};
public class CheckException
{
public static void main(String[] args)
{
System.out.println("Hello World!");
try
{
temp();
}
catch (MyException e)
{
}
}

static void temp()
{
}
}

On compiling, I get an error. However if MyException extends from RuntimeException, I dont get any error.
From this what I infer is "All USER DEFINED EXCEPTIONS that extend from Exception are treated as Checked Exception". Please let me know if this correct.

To make things really weird , now consider this

import java.io.*;
class MyException extends Exception
{
};
public class CheckException
{
public static void main(String[] args)
{
System.out.println("Hello World!");
try
{
temp();
}
catch (MyException e)
{
}
temp1();
}
static void temp1()throws Exception
{
throw new Exception();
}
static void temp()throws MyException
{
}
}
On compiling, I get the following error

CheckException.java:17: unreported exception java.lang.Exception; must be caught or declared to be thrown
temp1();
^

Thanks & Regards,
Sandeep
[ January 17, 2006: Message edited by: Sandeep MP ]
 
Aleksander Zielinski
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep,

In first program your temp() method does NOT throw any exception, and since "All USER DEFINED EXCEPTIONS that extend from Exception are treated as Checked Exception" and you are trying to catch Checked Exception something (in this case temp() method) has to throw it.

In the second one temp1() method throws Exception so it has to be in the try block.
[ January 17, 2006: Message edited by: Aleksander Zielinski ]
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now should I consider Exception as checked or unchecked exception???
 
Thomas Drew
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exception should be considered checked. Only runtime exception are unchecked.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not understand what is your confusion, Sandeep. I thought it was already very clear that


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.


What is it that you have trouble understanding? Gagan and Enrique also explained it very well.

Once again, an exception that is a RuntimeExcepion or an Error is unchecked, all other exceptions are checked.

Now, Sandeep, comrade, tell me what it is that you do not understande of this statement, please.

Regards,
Edwin Dalorzo.
[ January 17, 2006: Message edited by: Edwin Dalorzo ]
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I will try to explain the thing that I am confused with.

If I consider Exception to be checked, then I should expect the following code to give me an error

try
{
temp();
}
catch(Exception e)
{
}

where temp is defined as follows

void temp()
{
}
Please note that the method temp() does not throw any exception.
However when this code snippet is compiled, I don't get any error
This makes me think that Exception is Unchecked.However the JLS conveys that Exception is Checked . Please let me what you think about this.

Thanks for trying to help me,
Sandeep
 
Aleksander Zielinski
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep,

If method you are calling throws Exception you have to handle it or declare, because your method throws CHECKED EXCEPTION, it is expliitly declared in method signature. Compiler has to make sure you know about and that you are going take care of that.

In your code snippet catch clause catches exception of type Exception which can be RuntimeException as well, so it doesn`t have to be declared by temp() method and compiler doesn`t even check if there`s RuntimeException declared or not. It just assumes your method could throw RuntimeException so catch clause catching exception of type Exception is legal and code compiles.
[ January 18, 2006: Message edited by: Aleksander Zielinski ]
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi sandeep,

i think this is an interesting anomaly... my personal explanation is that generally, instead of catching an exception of the type that is thrown, it is also possible to catch a parent class of it, eg.

instead of

catch(InterruptedIOException e),

you can also use the code

catch(IOException e),

as IOException is a parent class of InterruptedIOException.

so, my solution is: although Exception itself is a checked Exception, it is also the parent class of the UNchecked exceptions, and as it is not possible to check for every possible runtime exception at compile time (btw. this impossibility can be proved), it seems you can define catch(Exception e) anywhere in the code (even empty try{} block is possible, maybe because of multithreading? or because of convenience?)

when reading it, i also thought it is somewhat inconsistent to inherit an UNchecked exception from a checked one (ie. Exception)... i was wondering why there are not two types of base classes for exception, e.g. "CheckedException" and "UncheckedException", which possibly both could extend Throwable.

cheers
[ January 18, 2006: Message edited by: Tilo Hemp ]
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sandeep MP:
Hi,
Please note that the method temp() does not throw any exception.
However when this code snippet is compiled, I don't get any error
This makes me think that Exception is Unchecked.However the JLS conveys that Exception is Checked . Please let me what you think about this.

Thanks for trying to help me,
Sandeep


Hi Sandeep, Exception and all child classes of Exception or checked exceptions. You can catch checked excpetions in you catch block only if your code have chances of throwing that exception. But because Exception is parent class of RuntimeException it is allowed to catch that.

As per OOPS wherever a sub class is expected a super class is allowed. It means that you can do the following:

Exception ex = new RuntimeException()

where as reverse is not valid:
RuntimeException ex = new Exception(); // wrong

So it tells that when you are expected to catch RuntimeException or child classes (NuberFormatException) it is allowed to catch Exception, Throwable.

I hope you understood now.
 
Sandeep Prabhakar
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok folks, I now understand it. Thanks.
Hey Tilo, can you please send me an example that compiles with only try block and having no matching catch or finally block. I tried doing the same but got a compiler error.

Cheers,
Sandeep

[ January 18, 2006: Message edited by: Sandeep MP ]
[ January 18, 2006: Message edited by: Sandeep MP ]
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sandeep MP:
Ok folks, I now understand it. Thanks.
Hey Tilo, can you please send me an example that compiles with only try block and having no matching catch or finally block. I tried doing the same but got a compiler error.

Cheers,
Sandeep



Each try block should be followed by either catch or finally block. Its not possible with out that to compile.
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh yes, I think there was a misunderstanding... I meant an empty try block followed by a catch block, eg.

try{
// no code here
}catch(Exception e){
// maybe some code here
}

sorry for the confusion...

greetings
 
Enrique Villamizar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everybody: about this interesting subject I�m gonna make up my mind:

1) A checked exception (that is, subclasses of Exception but not RuntimeException) must require that the method that contains it has to define explicitly what action is to be taken if the abnormal condition (NOT error) arises. There are two ways of doing this:
1.1 Handle the exception by using the try � catch block. The catch block must name the expected exception class or a superclass.
1.2 Declare exceptions that a method can throw, this is like passing the buck and �letting the exception pass down to the next method in the stack� (K&B book - java version 1.4- page 249).

Now Sandeep why does your following code (adapted) compile?

Because temp() is in the try-catch block but to be honest since temp() doesn�t throw any exception that isn�t necessary!
What happens if I add throws Exception at �//3 ? Compile, but try-catch block is necessary, at this point I could omit the try-catch block (passing the buck) and add throws Exception at �//1
Until here I think I understand well, but
Now let�s make a little change:

public static void main(String[] args){//1
try {
temp();
}//try
catch (MyException e){ //2 a little change
}//catch()
}//main()

static void temp(){//3
}//temp()
}//class


Compiler ERROR: exception MyException is never thrown in body of corresponding try statement
Why now throws MyException at�//3 is required?
Why throws Exception at�//3 doesn�t work if MyExceptions is a subclass of Exception?
Are there special rules when working with a user-defined exceptions? What is the difference between throws and throw? Why I came back to this topic if yesterday I was happy because I thought I Understood exceptions? Why my Time for taking the exam is running out? Why I have to learn Java and English as well? Sandeep is your fault! (Only joking) Sorry, you all don�t need to answer the last three questions!
Thanks for your help!

Enrique Villamizar
(P.S. English isn't my first language)
[ January 18, 2006: Message edited by: Enrique Villamizar ]
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi enrique!

if in your example, MyException extends RuntimeException, then the code would work without declaring MyException to be thrown from temp(). on the other hand, if MyException _is_ a subclass of Exception, then it is clear to the compiler that it is not a subclass of RuntimeException, and so it is known to be a checked exception.

as said above, when catching "Exception", it is not clear which subclass is meant (checked or unchecked), so it is legal to catch it any time, although it is a checked exception. every other checked exception may only be catched if itself (or a subclass of it) is declared to be thrown in the try block.
 
Enrique Villamizar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:

Thanks Tilo I got it. I was wondering if someone could tell me how to handle user-defined exception(checked). In fact, I need a plain explanation about the difference between throws and throw keywords. I think throw is needed when you use your own checked exceptions?!? or where I can get information about it!

Thanks again!

Enrique Villamizar
�Happiness isn�t a station to get but a way of travelling�
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Enrique Villamizar:
Hi:

I was wondering if someone could tell me how to handle user-defined exception(checked). In fact, I need a plain explanation about the difference between throws and throw keywords. I think throw is needed when you use your own checked exceptions?!?


Not necessarily. You can use throw an Exception to throw back an exception which you catch in your catch block or you can throw exceptions which are not user defined exceptions(but avoid this).
 
Enrique Villamizar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello KJ:


Why if I ommit throw new MyException the code doesn't compile?
ERROR: exception MyException is never thrown in body of corresponding try statement
I noticed that this happens with all checked exception, but why doesn't it compile if there is a try-catch block in the method body? Why I have to use throw (NOT throws) and create an object of MyException class?
I also notice that the same happens Changing MyException for IOException or another checked exception.

Once again thanks a lot for your patience!

Enrique Villamizar
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Enrique,

I dont have your complete code. But I do understand that your MyException extends from Exception so it is checked exception. So if there are chances of getting exception in your try block then only you can catch Checked Exception.
So if you avoid the line: throw new MyException(); there is no chances that your try block will throw this exception. Thats why you are getting exception in compilation.

Thats the difference between checked and unchecked exception.

throws is used declare that method may throw some exception.

throw is something you are throwing exception.

Some more details in the following thread:
http://www.coderanch.com/t/252511/java-programmer-SCJP/certification/One-more-exceptions

Hope you got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!