Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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.
 
There were millions of the little blood suckers. But thanks to this tiny ad, I wasn't bitten once.
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic