Like this tutorial? Read more... The free SCJP ebook
Witscale Test Center

Previous Page Next Page Contents Index

Valid XHTML 1.0!

Flow Control and Exceptions


Flow control statements
  1. Conditional flow control statements like if, if-else and switch-case
  2. Looping statements such as for, while, do-while
  3. Exception handling statements like try-catch-finally, throw
  4. Ad hoc flow control statements like break, continue with or without label:
[More in ebook]
switch statement
  • switch(expression){
      case ConstantExpression: statement(s);
      case ConstantExpression: statement(s);
      .
      .
      .
      default: statement(s);
    
    }
    
  • The type of the expression must be char, byte, short, or int, or a compile-time error occurs.
  • long primitive cannot be passed in switch or case statements. As switch accepts int, passing long will require to cast it to int.
  • Object reference cannot be passed to switch or case statement. Only constant expressions can be passed. Therefore, only expression that can be evaluated at compile time is allowed. These can be numeric literals or static final variables.
  • Every case expression must be evaluated to be unique.
  • 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 atmost 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, switch statement does nothing.

[More in ebook]

break and continue
  • A break statement transfers the control out of an enclosing statement. break used within a loop breaks the execution of the current loop. In case of nested loops, the break statement passes the control to the immediate outer loop.
  • A continue statement breaks the current iteration and moves to next iteration.
  • break and continue with labels.
    • Labels specify the target (statement) for continue and break.
    • continue with label does not jump to the labeled statement but instead jumps to the end of the labeled loop.
    • 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).



[More in ebook]

Exceptions
  • Whenever a program violates the syntax/semantics of Java, the JVM signals this error to the program as an exception.
  • When an exception occurs, the flow is transferred from that point to a new point that can be specified by the programmer.
  • 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 the exceptions explicitly, using throw statements.
  • Throwing an exception consists of creating an exception object and handling it to the java runtime system. Only objects of java.lang.Throwable class can be thrown by JVM or by using 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 foreseen errors.
  • With exception handling, Java separates the error handling code from regular code, making the code more clean, readable and manageable.

[More in ebook]
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 errors 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.



Throwable class hierarchy

Checked and Unchecked Exceptions
  • Checked Exceptions
    • A checked exception is 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.
    • Checked exception forces 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.
    • Class java.lang.Error and its subclasses also are unchecked.
    • 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.
    • Runtime exceptions do not need to be caught or declared.
    • Runtime Exceptions
      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 anObject = new Integer(10);
       System.out.println((String) anObject);    // ClassCastException occurs at runtime.
       
      

[More in ebook] Handling an exception
For handling exception programmatically, enclose the statements that might throw an exception within a try block.
 try {
 .
 .
 }catch(Throwable exception) {
 }

 try {
 .
 .
 }finally {
 }


  • The 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.
  • The finally {..} clause.
    • 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.
  • throws clause in method declaration. It is sometimes desirable for 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 [More in ebook]
Related SCJP Objective

Section 2 : Flow Control, Assertions, and Exception Handling
  1. Write code using if and switch statements and identify legal argument types for these statements.
  2. 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.
  3. Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions.
  4. 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).
  5. Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions.
  6. Identify correct statements about the assertion mechanism.


Previous Page Next Page Contents Index Top of this page

Valid CSS!