Java Reference
In-Depth Information
TABLE 11-12 Exceptions Thrown by the Methods of the class String
Method
Exception Thrown
Description
String(String str)
NullPointerException
str is null .
StringIndexOutOfBounds
Exception
The value of a is not
a valid index.
charAt( int a)
indexOf(String str)
NullPointerException
str is null .
lastIndexOf(String str)
NullPointerException
str is null .
StringIndexOutOfBounds
Exception
The value of a is not
a valid index.
substring( int a)
The value of a and/or
b is not a valid
index.
StringIndexOutOfBounds
Exception
substring( int a, int b)
Checked and Unchecked Exceptions
In discussing file input/output, Chapter 3 stated that if an input file does not exist when
the program executes, the program throws a FileNotFoundException . Similarly, if a
program cannot create or access an output file, the program throws a
FileNotFoundException . Until now, the program we have used ignored this type of
exception by including the throws FileNotFoundException clause in the heading of
the method. If we did not include this throws clause in the heading of the method main ,
the compiler would generate a syntax (compile-time) error.
On the other hand, in programs that used the methods nextInt and nextDouble ,we
did not include the code to check whether the input was valid or a throws clause (there
was no need to do so) in the method heading to ignore these exceptions, and the
compiler did not generate a syntax error. Also, we were not concerned about situations
such as division by zero or array index out of bounds. If these types of errors occurred
during program execution, the program terminated with an appropriate error message.
For these types of exceptions, we did not need to include a throws clause in the heading
of any method. So, the obvious question is: What types of exceptions need the throws
clause in a method heading?
Java's predefined exceptions are divided into two categories: checked exceptions and
unchecked exceptions. Any exception that the compiler can recognize is called a
checked exception. For example, FileNotFoundExceptions are checked exceptions.
1
1
 
Search WWH ::




Custom Search