String FileName;
BufferedReader File1;
...
File1=new BufferedReader(new FileReader(FileName));
Note there are three objects here - the String FileName which is the actual ascii name of the file you wish to open, an object of type FileReader which is a fairly general reader for reading data a character at a time from a text file, and an object of type BufferedReader which includes methods to tell the FileReader to read in whole lines at a time with the method readLine().
However, if you try to declare a BufferedReader in this fashion, the compiler will give you the error message:
FileTest.java:16: unreported exception java.io.FileNotFoundException;
must be caught or declared to be thrown
File1=new BufferedReader(new FileReader(FileIn));
^
This occurs because opening any file automatically entails the risk of misspecification of the file name. If this happens, Java forces you to take care of this by "catching the exception". The exception type (FileNotFoundException) should be clear in meaning - an exception of type FileNotFoundException occurs when the system cannot find the file you specified.
Many methods and classes in java raise exceptions in the way that the constructor for the FileReader did here. (For example, if you were to execute the statement Integer.parseInt("aqr") the system would raise the exception java.lang.NumberFormatException: aqr to indicate that aqr is not a proper String representation of an integer.
A NumberFormatException is handled by default by terminating the program. The designers of the File classes decided that this was not an adequate solution for FileNotFoundException so they forced you to handle the exception one way or the other.
Here is how you would actually handle the creation of a BufferedReader so as to properly do the exception:
try
{
InFile=new
BufferedReader(new FileReader(FileIn));
}
catch(FileNotFoundException e)
{
System.out.println("ERROR:
"+e+" for file "+ FileIn);
System.exit(0);
}
The try command says to attempt to execute the statement(s) in the brackets that follow and, if this fails, to find the appropriate catch statement containing the correct exception and execute what is between the brackets after that catch statement. In this case, if FileIn is not the name of a file, then we will print out an error message and exit the program. The error message will specify the exception (this is what the e after "ERROR:" does) and print out "for file" and the name of the file that failed.
Notice that it is possible for one try to have many catch statements (one for each exception that can occur) and that you can add a special clause at the end called a "finally" clause that will always be executed, whether the exception occurs or not. In general, it looks something like this:
try
{
try stuff
}
catch(Exception1 e1)
{
Exception1 stuff
}
catch(Exception2 e2)
{
Exception2 stuff
}
...
catch(ExceptionN eN)
{
ExceptionN stuff
}
finally
{
finally stuff
}