Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 2 ■ JAVA SYNTAX


know immediately when we need to catch checked exceptions. Runtime exceptions (as the name
implies) can only be caught at run time, so Eclipse can't warn us about those as we write our code.
Checked exceptions represent things beyond the program's control, such as bad user input or a file
not existing. Runtime exceptions represent things that can be fixed with more or better code. One school
of thought says that checked exceptions represent things the program should recover from. For example,
if the program encounters a missing file (that is, some method gets an IOException when it expects a file
handle), the program should ask the user where the file is or let the user cancel the operation. Runtime
exceptions represent errors (usually oversights) in the code that developers should fix. If you get a
NullPointerException, you don't ask the user to do anything (though you might tell the user to call
customer support and report the problem). Instead, you fix the point in the code where something is
passing null when it shouldn't. One concept that nearly all experienced programmers embrace is
defensive programming, which means we try to not let things get to a point where exceptions can
happen. Instead, we do things like checking to see whether something is null before we try to use it.
As it happens, IllegalArgumentException is a runtime exception. If you remove the try-catch blocks
from AverageTest, you get no error. However, because I can anticipate the problem, I elect to specifically
throw that error, so that I can attach a meaningful error message.

Blocks


Blocks are units of code that (usually) consist of more than one line and are defined by brace characters
({}). (Brace characters have several names, which can be pretty far-fetched. Throughout the book, I call
them braces, for the sake of consistency.)
Braces define blocks of code for methods, classes, and various statements (such as if and for). Let's
look at a simple block from the AverageImpl class in Listing 2-16:

Listing 2-16. A simple block

for (int i = 0; i < ints.length; i++) {
result += ints[i];
}

Static BlocksStatic blocks are handy bits of code that let you define one block of code and have it be
included in every constructor. Let's consider an example (in the form of a different class) in Listing 2-17.

Listing 2-17. Static block example

package com.bryantcs.examples;

public class StaticBlockClass {

private static String name;
private String whichOne;

static {
name = "StaticBlockClass";
}
Free download pdf