Java Reference
In-Depth Information
7.5 The
try...catch
Construct
When a program is trying to read data, errors can arise. There may be a problem with the device, we may be trying to
read beyond the end of the file, or the file we are asking to read from may not even exist. Similarly, when we attempt to
write data to a file, the device may be locked or unavailable, or we may not have write permission. In such cases, Java
throws an IO (input/output) Exception”.
Whenever there is the possibility that a method may trigger an I/O error, either by performing some I/O
operation itself or by calling a method that does, Java requires that the method declare this. One way to do so is to use
throws IOException
in the method header, as in the following:
public static void main(String[] args) throws IOException {
Another way to handle input/output errors is to use the
try...catch
construct. Suppose a program contains
this statement:
Scanner in = new Scanner(new FileReader("input.txt"));
When run, if the program cannot find a file called
input.txt
, it will halt with a “file not found exception” error
message. We can avoid this as follows:
try {
Scanner in = new Scanner(new FileReader("input.txt"));
}
catch (IOException e) {
System.out.printf("%s\n", e);
System.out.printf("Correct the problem and try again\n");
System.exit(1);
}
The
try
block consists of the word
try
followed by a block (zero or more statements enclosed in braces). Java
attempts to execute the statements in the block.
The
catch
part consists of the word
catch
followed by an “exception type” in brackets, followed by a block. In this
example, we expect that an I/O exception might be thrown, so we use
IOException e
after
catch
. If an exception is
indeed thrown, the statements in the
catch
block are executed.
In this example, suppose the file
input.txt
exists. The
Scanner in…
statement will succeed, and the program will
continue with the statement
after
the
catch
block. But if the file does
not
exist or is not available, the exception will be
thrown and caught with the
catch
part.
Search WWH ::
Custom Search