Java Reference
In-Depth Information
The following snippet of code uses a valid sequence of multiple
catch
blocks. The
ArithmeticException
class
is a subclass of the
RuntimeException
class. If both of these exceptions are handled in
catch
blocks for the same
try
block, the most specific type, which is
ArithmeticException
, must appear before the most generic type, which is
RuntimeException
.
try {
// Do something, which might throw Exception
}
catch(ArithmeticException e1) {
// Handle ArithmeticException first
}
catch(RuntimeException e2) {
// Handle RuntimeException after ArithmeticException
}
Checked and Unchecked Exceptions
Before I start discussing checked and unchecked exceptions, let's look at a Java program that reads a character from
the standard input. You have been using the
System.out.println()
method to print messages on the standard
output, which is typically the console. You can use the
System.in.read()
method to read a byte from the standard
input, which is typically the keyboard. It returns the value of the byte as an
int
between 0 and 255. It returns -1 if
the end of input is reached. The following is the code that reads a byte from the standard input and returns it as a
character. It assumes that the language you are using has all alphabets whose Unicode values are between 0 and 255.
The
readChar()
method has the main code. To read a character from the standard input, you will need to use the
ReadInput.readChar()
method.
// ReadInput.java
package com.jdojo.exception;
public class ReadInput {
public static char readChar() {
char c = '\u0000';
int input = System.in.read();
if (input != -1) {
c = (char)input;
}
return c;
}
}
Try to compile the
ReadInput
class. Oops! The compiler could not compile
ReadInput
class. It generated the
following error message:
"ReadInput.java": unreported exception java.io.IOException; must be caught or declared to be thrown
at line 7, column 31
The compiler error is pointing to line 7 in the source code:
int input = System.in.read();