Java Reference
In-Depth Information
14.3
Point out the problem in the following code. Does the code throw any exceptions?
long value = Long.MAX_VALUE + 1 ;
System.out.println(value);
14.4
What does the JVM do when an exception occurs? How do you catch an exception?
14.5
What is the printout of the following code?
public class Test {
public static void main(String[] args) {
try {
int value = 30 ;
if (value < 40 )
throw new Exception( "value is too small" );
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println( "Continue after the catch block" );
}
}
What would be the printout if the line
int value = 30 ;
were changed to
int value = 50 ;
14.6 Show the output of the following code.
public class Test {
public static void main(String[] args) {
for ( int i = 0 ; i < 2 ; i++) {
System.out.print(i + " " );
try {
System.out.println( 1 / 0 );
public class Test {
public static void main(String[] args) {
try {
for ( int i = 0 ; i < 2 ; i++) {
System.out.print(i + " " );
System.out.println( 1 / 0 );
}
catch (Exception ex) {
}
}
}
catch (Exception ex) {
}
}
}
}
}
}
(a)
(b)
14.3 Exception Types
Exceptions are objects, and objects are defined using classes. The root class for
exceptions is java.lang.Throwable .
Key
Point
The preceding section used the classes ArithmeticException and InputMismatch-
Exception . Are there any other types of exceptions you can use? Can you define your own
exception classes? Yes. There are many predefined exception classes in the Java API. Figure 14.1
shows some of them, and in Section 14.9 you will learn how to define your own exception
classes.
 
 
Search WWH ::




Custom Search