Section 2: Flow Control, Assertions, and Exception Handling ( Chapter 5 )

  • Write code using if and switch statements and identify legal argument types for these statements.

  • Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution.

  • Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions.

  • Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).

  • Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions.

  • Identify correct statements about the assertion mechanism.

Study Notes

The if statement affects control flow based on a boolean expression. The switch statement affects control flow based on a non-long integral expression. The break statement exits the loop or switch statement, and the continue statement skips the rest of the current iteration in a loop. Transfer of control using labeled break and continue statements should be understood.

Exceptions are objects in Java. An exception is either checked or unchecked. Methods must explicitly declare any checked exceptions they throw but do not catch. Declaration of try, catch, and finally blocks must follow certain rules. There are three basic control flow scenarios that may occur in conjunction with exceptions. The control flow for each of these scenarios should be understood:

  1. When no exception is generated.

  2. When an exception is thrown within a try block, and a catch block handles the exception.

  3. When an exception is thrown within a try block, and no catch block handles the exception.

The finally block is always executed.

The boolean expression of an assert statement will be evaluated if assertions are enabled during runtime, and an java.lang.AssertionError will be thrown if the result is false. An augmented form of the assert statement allows a value to be displayed as a detailed error message. AssertionError is a direct subclass of Error. The assertion mechanism should be used to write correct programs, and the exception facility should be used to make them robust.