• 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

need you help!!!

 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
//-------------------------the code---------------------//
interface AnInterface
{
public void methodOne() throws Exception;
}

class AnInterfaceImpl implements AnInterface
{
public void methodOne()
{
System.out.println("I will never throw an exception");
}
}
public class ATest
{
public static void main(String args[])
{
AnInterface ai = new AnInterfaceImpl();
ai.methodOne();
}
}
Attempting to compile and run the above code
A) Will cause a compile time error. (Line 5 : Exception must be caught or thrown by main(String))
B) Will cause a compile time error for Class AnInterfaceImpl. The method methodOne() be declared with "throws Exception".
C) Will cause no compile time error and print "I will never throw and Exception the screen".
D) Will Cause a run time error .
the given ans is :A;
when I change the main method declarationof class Atest to : public static void main(String args[]) throws Exception
everything is ok!
But I think in the main method ,the instance ai only invoke the method methodOne which override superclass's methodOne,and in it��s declareation ,it doesn��t throws any Exception ,as a result ,the main needn��t throws the Exception.
but ......the facts wins me!
could you give me the reason!

 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The checked exceptions when thrown need to be caught or declared. And when declared need to be thrown.
Note that if the type of ai were AnInterfaceImpl the exception is not declared so no problem if not throwing it.
 
It's a pleasure to see superheros taking such an interest in science. And this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic