Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Aru
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
In the code given below, If I compile I get the
C:\Java\bin>javac Test.java
Test.java:24: Exception MyException must be caught, or it must be declared in the throws clause of this method.
tc.m1();
^
1 error
As the error says the "Exception MyException must be 'caught' or declared in throws clause", I have the catch in the try block to catch the exception, Why does it still gives an error. ?
But if I code the throws clause in the main method it does'nt give the Error.
Can anyone explain. ?
class MyException extends Exception {}
public class Test
{
public static void main(String[ ] args)
{
Test tc = new Test();
try
{
tc.m1();
}
catch (MyException e)
{
tc.m1();
}
finally
{
tc.m2();
}
}
public void m1() throws MyException
{
throw new MyException();
}
public void m2() throws RuntimeException
{
throw new NullPointerException();
}
}
Thx in advance.
Aruna
 
kishen uchil
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there.
this is the code that u specified
class MyException extends Exception {}
public class Test
{
public static void main(String[ ] args)
{
Test tc = new Test();
try
{
tc.m1();
}
catch (MyException e)
{
tc.m1();
}
finally
{
tc.m2();
}
}
public void m1() throws MyException
{
throw new MyException();
}
public void m2() throws RuntimeException
{
throw new NullPointerException();
}
}

actually myfriend what is happening is that u are catching the exception int try block and that works fine.but an exception again arises in your catch block(tc.m1) and this exception is not bieng caught.if u put a try catch block like this inside the catch block it compiles fine:
catch (MyException e)
{
try{
tc.m1();
}
catch(MyException a)
{
}
}
you can either do this or u can specify a throws clause along with the main method.
hope this helps.
p.s:RuntimeException and all its sub classes are unchecked exceptions and they donot need to be caught .
 
Aru
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kishen Thx.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic