To tell Java what to do when exceptions are thrown, you have two choices.
First, you can embed a group of statements, some of which may throw
exceptions, in a try
catch
statement, in which you specify
explicitly what Java is to do when particular exceptions are thrown. You
learn about this approach in Chapter 32.
Second, you can indicate that a method contains statements that may throw
exceptions with which you do not wish to deal in that method. You so
indicate by adding the keyword throws
and the name of the
exception class, or a superclass of the exception class, to the method
definition. To handle all sorts of inputoutput exceptions, including
instances of the FileNotFoundException
class, you use
IOException
as the name of the exception class:
Exception-indicating keyword --* *-- Exception class | | v v public class Demonstrate { ------ ----------- public static void main(String argv[]) throws IOException { ... } }
Java insists that you use either a try
catch
statement or the
throws
keyword, to force you to think about what you want to
happen in the event that a failure occurs.
Of the two approaches, you see the throws
keyword in this chapter,
because the focus of this chapter is file input streams, not exception
handling. In general, however, using a try
catch
statement
is better programming practice, because such statements place the solution
close to where the problem occurs.