Wednesday, 19 September 2012

Differentiate between checked and unchecked exception with an example?



·        A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.  Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method

import java.io.*;
public class writefile
{
  public static void main(String[] args)throws IOException
  {     
      Writer output = null;
      File file = new File("write.txt");
      output = new BufferedWriter(new FileWriter(file));
      output.write("Prem Bharti");

      output.close();
      System.out.println("Your file has been written");
  }
}
·        Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
class division
{
    public static void division(int x, int y)
    {
        try
        {
            System.out.print(x/y);
        }
        catch(ArithmeticException a)
        {
            System.out.print("Don't divide something wid zero | " +a);
        }  
    }
}
public class uncheckedexception extends division
{
    public static void main(String[] s)
    {
        division(1, 0);
    }
}
Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.
More Details

No comments:

Post a Comment