hi ...all i know exception checking is done on a piece of block.through try/catch block..the catch statement give us the message.
but i was surprised to see a java program like below
import java.io.*;
class WriteTextFile {
public static void main ( String[] args ) throws IOException { String fileName = "reaper.txt" ;
FileWriter writer = new FileWriter( fileName );
writer.write( "Behold her, single in the field,\n" ); writer.write( "Yon solitary Highland Lass!\n" ); writer.write( "Reaping and singing by herself;\n" ); writer.write( "Stop here, or gently pass!\n" );
Yes, a method can throw exception. In your sample program main() method is meant to throw exception if it happens at runtime. Simple rule is that:
If you use a method m1() inside a method m2() and m1()throws a checked exception, then either you place m1() inside try-catch and handle the execption thrown by m1() or m2() should declare that it throws that execption.
A checked exception must be caught from the place of its use to somewhere up in hierarchy.
If you wanted to do anything meaningful you would wrap the code in a try/catch block as you have no control over the caller of the method. In my experience ,it is rare to see the main method throw an exception. The point of exception handling is to actually do something meaningful or die gracefully.