Witscale Test Center

Chapter summary


Chapter summary

This chapter covers the second SCJP objective devoted to the flow control in Java. We learned various flow control constructs, how they are declared and why they are used. We also learned how exception handling is done in Java. The assertions mechanism is a new addition with version 1.4. We learned how to use them for testing and debugging. This is a brief summary of the important concepts learned in this chapter.

 

       Java has four types of flow control statements

Conditional flow control statements like if, if-else and switch-case

Looping statements such as for, while, do-while

Exception handling statements like try-catch-finally, throw and throws

Ad hoc flow control statements like break, continue with or without label:

 

       The switch statement

The type of the argument must be char, byte, short, or int, or a compile-time error occurs.

A long primitive cannot be passed in switch or case statements. As switch accepts int, passing long will require casting it to int.

Object reference cannot be passed to switch or case statement. Only constant expressions that can be evaluated at compile time are allowed. These can be numeric literals or static final variables.

Every case expression must be evaluated to be unique.

The break statement may be used at the end of a case statement, to discontinue execution. If it is absent, the control falls through to execute all the remaining case statements and default statement (if any).

There can be at most only one default statement. The order of case statements and default can be anything.

If none of the cases match and there is no default case, the switch statement does nothing.

 

       The break and continue statements

The break statement transfers the control out of an enclosing statement. It is used within a loop to break the execution of the current loop. In case of nested loops, the break statement passes the control to the immediate outer loop.

The continue statement breaks the current iteration and moves to the next iteration.

 The break and continue with labels.

Labels specify the target (statement) for the continue and break statement.

continue with label does not jump to the labeled statement but instead jumps to the end of the labeled loop.

The same label identifiers can be reused multiple times as long as they are not nested.

Label names do not conflict with the same named identifier (variable, method or class name).

 

       Exceptions

An exception is said to be thrown from the point where it occurred and is said to be caught at the point to which control is transferred.

Programs can also throw exceptions explicitly, using throw statements.

Throwing an exception consists of creating an exception object and handing it to the Java runtime system. Only objects of java.lang.Throwable class can be thrown by JVM or by using the throw statement.

For example,

throw new SomeException("Exception message"); 

      SomeException must be the subclass of java.lang.Throwable.

Programmers can use the exception-handling constructs like (try-catch and try-catch-finally) to manage the foreseen errors.

With exception handling, Java separates the error handling code from regular code, making the code more clean, readable and manageable.

 

 

       Errors and Exceptions

There are two types of exceptions, an Error and an Exception.

An Error and an Exception are the direct subclasses of the Throwable class.

Errors are handled by Java system. Instances of Error are results of internal errors inside the Java runtime. Errors are rare and usually fatal.

All programmer-declared exceptions must be the subclasses of Exception class.

 

q        Checked Exceptions

A checked exception is a direct or indirect subclass of Exception excluding class RuntimeException and its subclasses.

Checked Exceptions are checked by the compiler to see if these exceptions are properly caught or specified. If not, the code will fail to compile.

A Checked exception forces the client program to deal with the scenario in which an exception may be thrown.

Checked exceptions must be either declared or caught at compile time.

 

       Unchecked Exceptions

Unchecked exceptions are RuntimeException and all of its subclasses, and class java.lang.Error and its subclasses.

Unchecked Exceptions are not checked by the compiler. The compiler will not insist that client program/method should declare each exception thrown by a method or even handle it.

The unchecked or the runtime exceptions do not need to be caught or declared.

RuntimeException is a direct subclass of Exception. RuntimeException class and its subclasses represent exceptions, which may be thrown during normal operation of the JVM at runtime.For example, ClassCastException occurs when the code attempts casting of an object to an incompatible type.

Object obj = new Integer(10);

System.out.println((String) obj); // The ClassCastException

 

 

       Handling an exception

For handling exception programmatically, enclose the statements that might throw an exception within a try {..} block.

A try statement executes a block and oversees the execution of enclosed statements for exceptions. It also defines the scope for the exception handlers (defined in catch clause).

The try block must be accompanied by at least one catch block or one finally block.

The catch(Throwable throwable){..} clause of try block.

The catch clause contains the exception handling code.

The catch statement takes only the objects of Throwable type as an argument.

Statements in a catch block are executed whenever a particular exception it is catching actually occurs within the try block.

       Order of the exception handlers.

The special exception handlers should come before the generalized exception handler. Otherwise a compile time exception occurs.

A try block can have a finally clause which must come after all the catch clauses.

The finally clause always gets executed...

In case the try block completed normally i.e. no exception occurred within try block.

If exception occurs within try block and one of the catch blocks handled that exception.

In case, an exception occurred within try block that none of the catch block could handle.

Thus, the code in finally clause is always executed, unless the thread executing the try code dies.

The finally clause also helps in general cleanup and disposal of system resources at the time of try block exit.

The throws clause in method declaration.

It is sometimes desirable for a method to declare which exceptions it is going to throw instead of handling them. The client of the method can then decide how to handle the exception. The throws keyword is used to identify the list of possible exceptions that a method might throw.

       Assertions

Assertions are used to:

Document and test your assumptions

Verify your understanding about the code

Quickly find out a bug

Assertions are used by using assert statement.

How to use assertions

Compile:                       javac –source 1.4 myprogram.java

Enable assertions:              java –ea myprogram

Enable assertions in JRE libraries:     java –esa myprogram

Enable assertions in package:  java –ea:com.mypackage... com.mypackage.myprogram

Disable assertions in default package:   java –da:... com.mypackage.myprogram

Appropriate use of assertions

Don’ts

Do not use assertions to verify arguments of public method

Do not use expressions in assertion that cause side effect

Dos

Do use assertions to verify the control flow never reaches at certain places

Do use assertions to replace a switch statement with no default case with a switch statement that has assert false; in its default case.

Do use assertions to check the post-conditions and non-public preconditions of methods.