Java Reference
In-Depth Information
inStream =newFileReader(args[0]);
outStream=newFileWriter(args[1]);
//copy
while((ch=inStream.read())!=EOF){
outStream.write(ch);
}
}
catch(IndexOutOfBoundsExceptione){
System.err.println(
"usage:javaCopy1sourcefiletargetfile");
}
catch(FileNotFoundExceptione){
System.err.println(e); //relyone'stoString()
}
catch(IOExceptione){
System.err.println(e);
}
finally{//closethefiles
inStream.close();
outStream.close();
}
}
voidfoo()
throwsIOException{
thrownewIOException();
}
}
Notice that the closing of files in the finally-clause might cause an exception to be thrown.
We could either nest this closing of files within its own try-catch block or we could declare
that the method main might possibly throw an IOException . We do the latter here.
Exercise 5.15. Add the throw-statement to j--, adding it to your compiler and testing
it thoroughly. The throw-statement is straightforwardly compiled to JVM code using the
athrow instruction; for example,
thrownewIOException();
produces the following JVM code, which constructs, initializes, and throws the exception
object:
0:new #16;//classjava/io/IOException
3:dup
4:invokespecial#17;//methodjava/io/IOException."<init>":()V
7:athrow
Exercise 5.16. Add the try-catch-finally-statement to j--, adding it to your compiler and
testing it thoroughly.
Let us look at the code generated by javac for method main() (above):
publicstaticvoidmain(java.lang.String[]) throwsjava.io.IOException;
Code:
Stack=4,Locals=6,Args_size=1
0:aconst_null
1:astore_1
2:aconst_null
3:astore_2
4:new #2;//classjava/io/FileReader
7:dup
8:aload_0
 
Search WWH ::




Custom Search