Saturday, July 28, 2012

Checked vs Unchecked exceptions





  • Exception subclasses represent errors that a program can reasonably recover from. Except for RuntimeException and its subclasses (see below), they generally represent errors that a program will expect to occur in the normal course of duty: for example, network connection errors and filing system errors.
  • Error subclasses represent "serious" errors that a program generally shouldn't expect to catch and recover from. These include conditions such as an expected class file being missing, or an OutOfMemoryError.
  • RuntimeException is a further subclass of ExceptionRuntimeException and its subclasses are slightly different: they represent exceptions that a program shouldn't generally expect to occur, but could potentially recover from. They represent what are likely to be programming errors rather than errors due to invalid user input or a badly configured environment.

Unchecked exceptions:
·       ·        Represent defects in the program (bugs) - often invalid arguments passed to a non-private method. "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."

·      They DON'T have to be caught or declared thrown.

·     They are subclasses of java.lang.RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException

·        A method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)


Checked exceptions:
·        Represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
·        Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling.
·        They are subclasses of java.lang.Exception
·        A method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
·        It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).



List of Checked Exceptions-
Following are the list of various checked exception that defined in the java. lang package.
   Exception
   Reason for Exception
 ClassNotFoundException
This Exception occurs when Java run-time system fail to find the specified class mentioned in the program
Instantiation Exception
This Exception occurs when you create an object of an abstract class and interface
Illegal Access Exception
This Exception occurs when you create an object of an abstract class and interface
Not Such Method Exception
This Exception occurs when the method you call does not exist in class

2. Unchecked Exception:- These Exception arises during run-time ,that occur due to invalid argument passed to  method. The java Compiler does not check the program error during compilation. For Example when you divide a number by zero, run-time exception is raised.
  Exception
    Reason for Exception
Arithmetic Exception
These  Exception occurs, when you divide a number by zero causes an  Arithmetic Exception
Class Cast Exception
These Exception occurs, when you try to assign a reference variable of a class to an incompatible reference variable of another class
Array Store Exception
These Exception occurs, when you assign an array which is not compatible with the data type of that array
Array Index Out Of Bounds Exception
These Exception occurs, when you assign an array which is not compatible with the data type of that array
Null Pointer Exception
These Exception occurs, when you try to implement an application without referencing the object and allocating to a memory
Number Format Exception
These Exception occurs, when you try to convert a string variable in an incorrect format  to integer (numeric format) that is not compatible  with each other
Negative ArraySizeException
These are Exception, when you declare an array of negative size.




Rule of thumb:

Unchecked exceptions occur when there are logic errors with your program. Things that you as a programmer got wrong, and are able to fix in your own code (like dividing by zero, or going out of bounds on an array).

Checked exceptions come up when there are things that can go wrong that you can't control, like opening a file that doesn't exist, or making a connection to a server that isn't responding, etc.

 --------------------------------------------------------------------------

Exception Propagation 


               Method call stack

ExceptionDemo.method4  <--- Exception occurs
     ExceptionDemo.method3
     ExceptionDemo.method2
     ExceptionDemo.method1
     ExceptionDemo.main


 If not handled in any method, the exception is thrown and the application will stop



public class ExceptionDemo {
    
     public void method4(){
          int a=7;
          int b=0;
          int c=a/b;
     }
    
     public void method3(){
          this.method4();
          System.out.println("After method 4 completion");
     }

     public void method2(){
          this.method3();
          System.out.println("After method 3 completion");
     }
    
     public void method1(){
          this.method2();
          System.out.println("After method 2 completion");
     }

public static void main(String[] args){

     ExceptionDemo ex = new ExceptionDemo();
     ex.method1();
     System.out.println("After method 1 completion");
}   
}

Exception in thread "main" java.lang.ArithmeticException: / by zero
     at ExceptionDemo.method4(ExceptionDemo.java:7)
     at ExceptionDemo.method3(ExceptionDemo.java:11)
     at ExceptionDemo.method2(ExceptionDemo.java:16)
     at ExceptionDemo.method1(ExceptionDemo.java:22)
     at ExceptionDemo.main(ExceptionDemo.java:34)


-------------------------------------------------------------------------------------------------


public class ExceptionDemo {
    
     public void method4(){
          int a=7;
          int b=0;
          int c=a/b;
     }
    
     public void method3(){
          this.method4();
          System.out.println("After method 4 completion");
     }

     public void method2(){
          this.method3();
          System.out.println("After method 3 completion");
     }
    
     public void method1(){
          try{
              this.method2();
              System.out.println("After method 2 completion");
          }
          catch(Exception e)
          {
              System.out.println(e.getMessage());
          }
     }

public static void main(String[] args){

     ExceptionDemo ex = new ExceptionDemo();
     ex.method1();
     System.out.println("After method 1 completion");
}   
}

/ by zero
After method 1 completion
-----------------------------------------

            

              Writing own exception




public class MyCheckedException extends Exception{
    public MyCheckedException(String msg){
      super(msg);
    }

    public MyCheckedException(String msg, Throwable t){
      super(msg,t);
    }
}


Sunday, July 22, 2012

OVERRIDING vs OVERLOADING

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhM2c092Gvo2GoR85dC99tWPzZdoaoHg5b3szOhPxgaxYZXO-r1I6Q8AtPcQTZmkJTcWNWCLsc7s0LjKBvKLSJ_0wE5-D7xEDLt417qumzREYPJIkRkbug1JPXWxe0a1azMzDwgS8nVENs/s320/DSC_0573.JPG


OVERRIDING – when you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding.
Example:
public class BaseClass{
public void methodToOverride()
{
//Some code here
}
}
public class DerivedClass extends BaseClass{
public void methodToOverride()
{
//Some new code here
}
}

As you can see, in the class DerivedClass, we have overridden the method present in the BaseClass with a completely new piece of code in the DerivedClass.
What that effectively means is that if you create an object of DerivedClass and call the methodToOverride() method, the code in the derivedClass will be executed. If you hadn’t overridden the method in the DerivedClass then the method in the BaseClass would have been called.

The access specifier for an overriding method can allow more, but not less, access than the overridden method.
For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

OVERLOADING -  when you have more than one method with the same name but different arguments, the methods are said to be overloaded.
Example:
public class OverLoadingExample{
public void add(int i, int j)
{
int k = i + j;
}
public void add(String s, String t)
{
int k = Integer.parseInt(s) + Integer.parseInt(t);
}
}
As you can see in the example above, we have the same method add() taking two parameters but with different data types. Due to overloading we can now call the add method by either passing it a String or int 

Sunday, July 15, 2012

Delete v/s Truncate


DML (Delete)
DLL (Truncate/Drop)
Remove row one by one
Remove row in one execution and fast
Creates a roll back statement
Don’t create any log so cannot be rolled back
Allows conditional remove of record (where clause etc can be used )
Doesn’t allow conditional remove of record (all records have to be removed )
Triggers are fired
Triggers are not fired
Make entries in log file
Doesn’t make entries in log file
When you type DELETE.all the data get copied into the Rollback Tablespace first, then delete operation get performed.That's why when you type ROLLBACK after deleting a table, you can get back the data(The system get it for you from the Rollback Tablespace).All this process take time.
In TRUNCATE,it removes data directly without copying it into the Rollback   Tablespace.That's why TRUNCATE is faster.Once you Truncate you can't get back the data.
You can use DELETE statement on a parent table and if CASCADE ON DELETE is enabled then data from child table also get deleted. If CASCADE ON DELETE is NOT enabled and any of the child table has related then you can’t delete records from parent table.
You can’t truncate a parent table irrespective of whether the child table has any record or not. Truncate table statement will fail for parent table even if CASCADE ON DELETE is enabled.
Does not reset identity value of the table
Reset identity value of the table.
You may use DELETE statement against a view (with some limitations).
You can’t use TRUNCATE statement against a view.