• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

clarification on this Exceptioncode required

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
clarification on this Exceptioncode required//Contents of File AnInterface.java

public interface AnInterface
{
public void methodOne() throws Exception;
}


//Contents of File AnInterfaceImpl.java

public class AnInterfaceImpl implements AnInterface
{
public void methodOne()
{
System.out.println("I will never throw an exception");
}
}


Read the code below carefully.

public class ATest
{
public static void main(String args[])
{
AnInterface ai = new AnInterfaceImpl();
ai.methodOne();
}
}

when i execute this code i got a compiletime error saying unhandled exception by main ,why so ,actually ai.methodOne() is going to call the method in AnInterfaceImpl which is not throwing any Exception if i remove throws Exception i got the output as
"I will never throw an exception" what i was Expecting.
 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

when i execute this code i got a compiletime error saying unhandled exception by main ,why so ,actually ai.methodOne() is going to call the method in AnInterfaceImpl which is not throwing any Exception



But you are calling that method on a "AnInterface" reference which is what matters to the compiler.
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the compiler checks only the reference type not the referred object. So, there is an unhandled exception you get the error.
Try this and you get no error:


cheers
Bob

I am too slow.
 
Yes, my master! Here is the tiny ad you asked for:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic