final, finally and finalize () in Java

final

  • final is a keyword.
  • It is used to apply restriction on class, method and variables.
  • final class cannot be inherited, final method cannot be overridden and final variable cannot be changed.

finally

  • finally is a block followed by try or catch block.
  • finally block is executed whether exceptions are handled or not.
  • We put clean up code in finally block.

finalize ()

  • finalize is a method.
  • This method is associated with garbage collection, just before collecting the garbage by system.
  • It is called automatically.

Creating Custom Exceptions

  • The exceptions that we create on our own are known as custom exception.
  • These exceptions are created to generate a solution for anticipated errors as per programmer’s need.
  • A “Custom exception class” must be extended from “Exception class”.

Example : Program to create custom exception in Java

// CustomException.java

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

// CustomDemo.java

public class CustomDemo
{
      public static void main(String args[]) throws Exception
      {
           CustomDemo custom = new CustomDemo();
           custom.display();
      }
      public void display() throws CustomException
      {
           for(int i=2;i<20;i=i+2)
           {
                 System.out.println("i= "+i);
                 if(i==8)
                 {
                       throw new CustomException("My Exception Occurred");
                 }
           }
      }
}


Output:
i= 2
i= 4
i= 6
i= 8
Exception in thread "main" CustomException: My Exception Occurred
at CustomDemo.display(CustomDemo.java:11)
at CustomDemo.main(CustomDemo.java:4)