Java Reference
In-Depth Information
12.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);
12.4
What does the JVM do when an exception occurs? How do you catch an exception?
12.5
What is the output 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 output if the line
int
value =
30
;
were changed to
int
value =
50
;
12.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
);
}
catch
(Exception ex) {
}
}
}
}
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) {
}
}
}
(a)
(b)
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 12.1 shows some of them, and in Section 12.9 you will learn how to define your own
exception classes.
Search WWH ::
Custom Search