Author Topic:   Exceptions again
ranch hand
posted March 10, 2000 08:14 AM             

Please take a look at the following code.


class Test
public static void method1() throws Exception
catch(Exception e)
System.out.println("from catch(method1)");
public static void method2()

public static void main(String args[])
System.out.println("bye from main");

I getting an error like "Exception must be thrown or it must be caught. My question is method1 throws the Exception and it also catches that right. Then why does method2(which calls method1) have to declare that again in the throws or catch that.

Please help me out with this.

Thanks a lot.

[This message has been edited by sree (edited March 10, 2000).]

maha anna
posted March 10, 2000 12:35 PM             
Your qstn is correct. But you have put the throws Exception clause in the declaration part of method1() which you should not have been. Also note one more thing. If a method A() is declared as throwing an Exception by the throws clause (it may or may not actually throw the exception.It does not matter), whenever you use this methodName in a method invocation expression such as calling A() from another method B()
void B() {
you either catch the Exception thrown by A() or declare in the throws clause of B() that It is passing UP the Exception and the previous method which called A() has to handle that.

So for your code to work either you remove the 'throws' clause from method1() or declare method2() as either throws the Exception/ put a try-catch statmt to enclose the method1() invocation statement.
maha anna.

[This message has been edited by maha anna (edited March 10, 2000).]

Tony Alicea
posted March 10, 2000 12:40 PM             
Apparently the compiler is trusting you when you declare the Throws clause of method1(). That means that any method calling method1() has to catch the Exception. You said so, not the compiler.

You do catch an Exception in ONE block in method1(). What if you had more places inside that method where checked Exceptions could be thrown but were not caught? That's where you would need the Throws clause. If you take this clause off method1() the code will compile OK.

ranch hand
posted March 10, 2000 01:06 PM             
Thanks tony & anna.