Monday, 29 August 2011


Exceptions in Java

Throwable Class
The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.
The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.
Syntax
String getMessage()
void printStackTrace()
String toString()
Class Exception
The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).
Class RuntimeException
Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.
Class Error
Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Exception Statement Syntax
Exceptions are handled using a try-catch-finally construct, which has the Syntax
try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}
try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error. Again if the matching catch handler is not found execution
proceeds with the finally block and the default exception handler throws an exception.. If an exception is
generated within the try block, the remaining statements in the try block are not executed.
catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).
finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.
The following program illustrates the scenario.
try {
    <code>
} catch (<exception type1> <parameter1>) { // 0 or more
    <statements>
 
}
} finally {                               // finally block
    <statements>
}

Download
DivideException2.java
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
Below is a program showing the Normal Execution of the Program.
Please note that no NullPointerException is generated as was expected by most people
public class DivideException2 {
 
    public static void main(String[] args) {
      int result  = division(100,0);        // Line 2
        System.out.println("result : "+result);
    }
 
    public static int division(int totalSum, int totalNumber) {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            quotient  = totalSum/totalNumber;
 
      }
      catch(Exception e){
            System.out.println("Exception : "+ e.getMessage());
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
                  return quotient;
            }
 
      }
      return quotient;
    }
}
Output
null (And not NullPointerException)

–~~~~~~~~~~~~–

Rules for try, catch and finally Blocks

1. For each try block there can be zero or more catch blocks, but only one finally block. 
 
2. The catch blocks and finally block must always appear in conjunction with a try block.
 
3. A try block must be followed by either at least one catch block or one finally block.
 
4. The order exception handlers in the catch block must be from the most specific exception 
Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be An exception consists of a block of code called a try block, a block of code called a catch block, and the finally block. Let’s examine each of these in detail.
public class DivideException1 {
 
    public static void main(String[] args) {
      division(100,0);        // Line 2
        System.out.println("Main Program Terminating");
    }
 
    public static void division(int totalSum, int totalNumber) {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            quotient  = totalSum/totalNumber;
            System.out.println("Result is : "+quotient);
      }
      catch(Exception e){
            System.out.println("Exception : "+ e.getMessage());
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
            }
 
      }
    }
}
Download DivideException1.javaOutput
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
Main Program Terminating
As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and program execution is transferred to the catch statement. Because the exception is thrown from the try block, the remaining statements of the try block
are skipped. The finally block executes.
Defining new EXCEPTIONS!!
We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).
The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of Custom exception’s along with how the throw and throws clause are used.
class BadTemperature extends Exception{
      BadTemperature( String reason ){
            super ( reason );
    }
}
 
class TooHot extends BadTemperature{
 
      TooHot(){
            super ("Default messaeg : Hot");
    }
 
      TooHot(String message){
            super (message);
    }
}
 
class TooCold extends BadTemperature{ 
 
      TooCold(){
            super ("Default messaeg : Cold");
    }
 
      TooCold(String message){
            super (message);
    }
}
 
class TempertureObject{ 
 
      int temperature;
 
    TempertureObject( int temp ) {
      temperature = temp;
    }
 
    void test() throws TooHot, TooCold {
      if ( temperature < 70 ) throw new TooCold("Very Cold");
        if ( temperature > 80 ) throw new TooHot("Very Hot");
    }
}
 
public class ExceptionExample1{   
 
      private static void temperatureReport( TempertureObject batch ){
            try{   batch.test();
            System.out.println( "Perfect Temperature" );
        }
        catch ( BadTemperature bt ){
            System.out.println( bt.getMessage( ) );
        }
    }
 
    public static void main( String[] args ){
      temperatureReport( new TempertureObject( 100 ) );
        temperatureReport( new TempertureObject( 50 ) );
        temperatureReport( new TempertureObject( 75 ) );
    }
}
Download ExceptionExample.javaOutput
Output
Very Hot
Very Cold
Perfect Temperature

throw, throws statement

A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.
The general format of the throw statement is as follows:
throw <exception reference>;
The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created.
throw new TemperatureException(”Too hot”);
A throws clause can be used in the method prototype.
Method() throws <ExceptionType1>,…, <ExceptionTypen> {
}
Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.
When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throws and a throw statement.
public class DivideException3 {
 
    public static void main(String[] args) {
      try{
            int result  = division(100,10);
            result  = division(100,0);
            System.out.println("result : "+result);
      }
        catch(ArithmeticException e){
            System.out.println("Exception : "+ e.getMessage());
      }
    }
 
    public static int division(int totalSum, int totalNumber) throws ArithmeticException {
      int quotient = -1;
      System.out.println("Computing Division.");
      try{
            if(totalNumber == 0){
                  throw new ArithmeticException("Division attempt by 0");
            }
            quotient  = totalSum/totalNumber;
 
      }
      finally{
            if(quotient != -1){
                  System.out.println("Finally Block Executes");
                  System.out.println("Result : "+ quotient);
            }else{
                  System.out.println("Finally Block Executes. Exception Occurred");
            }
 
      }
      return quotient;
    }
}
Download DivideException3.javaOutput
Output
Computing Division.
Finally Block Executes
Result : 10
Computing Division.
Finally Block Executes. Exception Occurred
Exception : Division attempt by 0

Using break and return with Exceptions

This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finally block is executed always except when the return statement is executed.
public class ExceptionExample6 {
 
      public static void main(String[] args) {
 
            int x = 10, y = 2;
            int counter = 0;
            boolean flag = true;
            while (flag) {
            start:
                  try {
                        if ( y > 1 )
                               break start;
                        if ( y < 0 )
                               return;
                        x = x / y;
                        System.out.println ( "x : " + x + " y : "+y );
                  }
                  catch ( Exception e ) {
                        System.out.println ( e.getMessage() );
                  }
                  finally {
                        ++counter;
                        System.out.println ( "Counter : " + counter );
                  }
                  --y;
            }
      }
}
Download ExceptionExample6.javaOutput
Output
Counter : 1
x : 10 y : 1
Counter : 2
/ by zero
Counter : 3
Counter : 4

Handling Multiple Exceptions

It should be known by now that we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks.
import java.io.DataInputStream;
import java.io.IOException;
 
import javax.swing.JOptionPane;
public class ExceptionExample7{
    static int numerator, denominator;
 
    public ExceptionExample7( int t, int b ){
      numerator = t;
      denominator = b;
    }
 
    public int divide( ) throws ArithmeticException{
      return numerator/denominator;
    }
 
    public static void main( String args[] ){
 
      String num, denom;
 
      num = JOptionPane.showInputDialog(null, "Enter the Numerator");
      denom = JOptionPane.showInputDialog(null, "Enter the Denominator");
 
            try{
                numerator = Integer.parseInt( num );
                denominator = Integer.parseInt( denom );
            }
            catch ( NumberFormatException nfe ){
                System.out.println( "One of the inputs is not an integer" );
                return;
            }
        catch ( Exception e ){
                System.out.println( "Exception: " + e.getMessage( ) );
                return;
        }
 
            ExceptionExample7 d = new ExceptionExample7( numerator, denominator );
            try{
                double result = d.divide( );
                JOptionPane.showMessageDialog(null, "Result : " + result);
            }
            catch ( ArithmeticException ae ){
                  System.out.println( "You can't divide by zero" );
            }
            finally{
                  System.out.println( "Finally Block is always Executed" );
          }
    }
}
Download ExceptionExample7.java
Java Singletone Design Patterns:
Java has several design patterns Singleton Pattern being the most commonly used. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.
The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
One such scenario where it might prove useful is when we develop the help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications.
Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.

No comments: