Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unreported exception Problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Getting error:
unreported exception java.lang.Exception; must be caught or declared to be thrown
new B().call();

on replacing the lines with these

a) public static void main(String arg[]) throws TestException
gives:

unreported exception java.lang.Exception; must be caught or declared to be thrown
new B().call();
b) ^
public static void main(String arg[]) throws Exception
gives:

unreachable statement
new A().call();}catch(TestException e){throw e;System.out.println("me e eemeemme");}

c) public void call() throws TestException
gives:

unreachable statement
new A().call();}catch(TestException e){throw e;System.out.println("me e eemeemme");}

please help
 
Trivikram Kamat
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:
a) public static void main(String arg[]) throws TestException
gives:
unreported exception java.lang.Exception; must be caught or declared to be thrown
new B().call();


The method call() throws Exception which should be either caught in main() or thrown at higher level.
But, main doesn't catch it nor throws "Exception".
It throws TestException instead.

That's you get error unreported exception java.lang.Exception; must be caught or declared to be thrown
 
Trivikram Kamat
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:
b) ^
public static void main(String arg[]) throws Exception
gives:
unreachable statement
new A().call();}catch(TestException e){throw e;System.out.println("me e eemeemme");}


In this case, main() throws Exception, so there is no problems with throwing and catching Exceptions.
But the println() statement inside catch block in method call() is never reached.
This is because it rethrows the caught exception in previous line every time. So, the control flow goes outside the method - not reaching the println() statement.
 
Trivikram Kamat
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohitkumar gupta wrote:
c) public void call() throws TestException
gives:
unreachable statement
new A().call();}catch(TestException e){throw e;System.out.println("me e eemeemme");}


The reason is same as for (b)
But in this case, the main() throws Exception which is broader than TestException thrown by method call()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic