Java Reference
In-Depth Information
case 3:
System.out.println("You won a medal!!!");
break;
default:
System.out.println("You did not win a medal. Sorry.");
break;
}
Many programmers avoid the
switch
statement because it is so easy to produce a
bug such as that just described. In older programming languages the
switch
state-
ment was a more efficient way to execute the
if/else
statement, but this benefit is
not noticeable in Java.
The
try/catch
Statement
The
try/catch
statement “tries” to execute a given block of code (called the “
try
block”). The statement also specifies a second “
catch
block” of code that should be
executed if any code in the “
try
block” generates an exception of a particular type. It
uses the following syntax:
try {
<statements>
;
} catch (
<type> <name>
) {
<statements>
;
}
For example, the following code attempts to read an input file and prints an error
message if the operation fails:
try {
Scanner input = new Scanner(new File("input.txt"));
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("Error reading file: " + e);
}
If you wrap all potentially unsafe operations in a method with the
try/catch
syn-
tax, you do not need to use a
throws
clause on that method's header. For example, you
do not need to declare that your
main
method throws a
FileNotFoundException
if
you handle it yourself using a
try/catch
block.
Some variations of the
try/catch
syntax are not shown here. It is possible to
have multiple
catch
blocks for the same
try
block, to handle multiple kinds of
Search WWH ::
Custom Search