Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Wats Wrong With this Code ?

  Asked By: Bonni    Date: May 08    Category: Java    Views: 737
  

Plz explain in detail...

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

public class Test {

public void doSomething() {}

public void aMethod() {
try {
doSomething();
}catch(BadIndexException be) {
System.out.println("BadIndexException");
throw new BadIndexException(){};
}
}

public void anotherMethod() throws BadObjectException{
try {
doSomething();
}catch(BadObjectException be) {
System.out.println("BadObjectException");
}
}

public static void main(String[] args) throws BadObjectException{
Test t = new Test();
t.aMethod();
t.anotherMethod();
}
}

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Kiet Jainukul     Answered On: May 08

public void  anotherMethod() throws  BadObjectException{
try {
doSomething();
--------------->> }catch(BadObjectException be) {
System.out.println("BadObjectException");
}
}

--------------->> The doSomething method does not throw the BadObjectException.
so the catch statement wont be reached.

You can very well do with removing the try catch block.else have the doSomething
method defined with throws clause.

public void doSomething() throws BadObjectException

 
Answer #2    Answered By: Mae Roberts     Answered On: May 08

But the same doSomething() is used in aMethod(){} but Why don't it
throw error there ? Why only to anotherMethod ?
And plz  send me any good links for Java Exception Handling tutors..

 
Answer #3    Answered By: Freda Lane     Answered On: May 08

There are few points that you need to take care.

# BadObjectException belongs to Non-Runtime exception  category hence
if the called method throws  this exception then the calling method
should either catch the exception and handle the same OR re-throw the
exception in its throws clause.

# BadIndexException belongs to Runtime Exception category hence the
programmer is not forced to catch it or re-throw it. It is his wish
to decide on how to handle that exception OR simply ignore it.

# In your program, doSometing() does NOT throw any exception (I am
stressing on Non-Runtime exception.. ) hence an attempt to catch
exception will cause the compile time error. The reason is,
BadObjectException is never thrown in the body of corresponding try
statement.

Hope it clarifies your doubt. Write me if you need more details.

 
Answer #4    Answered By: Hooriya Khan     Answered On: May 08

Thanx a lot for clarifying my doubt. Really nice explaination...
Thanx once again for ur patience and helping nature.

 
Didn't find what you were looking for? Find more on Wats Wrong With this Code ? Or get search suggestion and latest updates.




Tagged: