Java Reference
In-Depth Information
Runtime exceptions are represented in the RuntimeException class, which
describes programming errors, such as bad casting, accessing an out-of-bounds
array, and numeric errors. Runtime exceptions are generally thrown by the JVM.
Examples of subclasses are listed in Table 14.3.
runtime exception
T ABLE 14.3
Examples of Subclasses of RuntimeException
Class
Reasons for Exception
ArithmeticException
Dividing an integer by zero. Note that floating-point arithmetic
does not throw exceptions (see Appendix E, Special Floating-
Point Values).
Attempt to access an object through a null reference variable.
NullPointerException
IndexOutOfBoundsException
Index to an array is out of range.
IllegalArgumentException
A method is passed an argument that is illegal or inappropriate.
RuntimeException , Error , and their subclasses are known as unchecked exceptions . All
other exceptions are known as checked exceptions , meaning that the compiler forces the
programmer to check and deal with them in a try-catch block or declare it in the method
header. Declaring an exception in the method header will be covered in Section 14.4.
In most cases, unchecked exceptions reflect programming logic errors that are unrecover-
able. For example, a NullPointerException is thrown if you access an object through a
reference variable before an object is assigned to it; an IndexOutOfBoundsException is
thrown if you access an element in an array outside the bounds of the array. These are logic
errors that should be corrected in the program. Unchecked exceptions can occur anywhere in
a program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate that
you write code to catch or declare unchecked exceptions.
unchecked exception
checked exception
Check
14.7 Describe the Java Throwable class, its subclasses, and the types of exceptions.
14.8 What RuntimeException will the following programs throw, if any?
Point
public class Test {
public static void main(String[] args) {
System.out.println( 1 / 0 );
public class Test {
public static void main(String[] args) {
int [] list = new int [ 5 ];
System.out.println(list[ 5 ]);
}
}
}
}
(a)
(b)
public class Test {
public static void main(String[] args) {
String s = "abc" ;
System.out.println(s.charAt( 3 ));
public class Test {
public static void main(String[] args) {
Object o = new Object();
String d = (String)o;
}
}
}
}
(c)
(d)
public class Test {
public static void main(String[] args) {
System.out.println( 1.0 / 0 );
public class Test {
public static void main(String[] args) {
Object o = null ;
System.out.println(o.toString());
}
}
}
}
(e)
(f)
 
 
Search WWH ::




Custom Search