Sunday, January 29, 2017

4-Exception Handling

reference: "Advanced Java Programming" by Utham.K.Roy

Every Exception extends another. The Root of all Exceptions being Throwable class.
  • Checked Exception: Exceptions that must be caught/declared-to-be-thrown explicitly.
  • Unchecked/also called runtime Exception: Exceptions that needn't be caught/declared-to-be-thrown explicitly.
Error : can neither be anticipated not be recovered from. Ex. OutOfMemory, StackOverflow, ClassFormat, NoClassFound, etc

Exceptions: Can be caught and handled.

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

printStackTrace():method prints a stack trace of the current exception on the standard error.
----------------------------------------------------------------------------------------------------

Try-Catch blocks :

There can be multiple catches blocks for a single try block. If all exceptions are subclasses of a certain Exception-Type, then just the at exception can be caught using the catch block as all the subclass exception will eventually be caught with just one catch block of the parent Exception.

However, if multiple catch blocks with different parents, then , instead of using multiple blocks, we could still use a single Catch block using the pipeline character(since JAVA SE7) as below example:
catch(ArrayIndexOutOfBoundsException|ArithmeticException e)
{
    System.out.println(e);
}

  • catch blocks must be arranged from most specific to most general. So, the following catch blocks are valid:
    • catch(ArrayIndexOutOfBoundsException e) {} catch(Exception e) {}
  • Here, the first catch block only catches ArrayIndexOutOfBoundsException whereas second one catches everything else.
----------------------------------------------------------------------------------------------------
'throw' keyword :
class Throw Test
{
     public static void main(String[] args) {
         try { throw new Exception("test");
               }
         catch(Exception e) { System.out.println(e); }
     }
}
  • Only objects that are instances of Throwable class (or one of its subclasses) may be thrown by the throw statement.
  • Similarly, only this class or one of its subclasses can be the argument type in a catch clause.


'throws' keyword :
  • This keyword is declared in the definition of a method with a certain exception 'A', to indicate that this method would possibly throw an exception of type 'A'.
  • multiple Exceptions can be declared with throws keyword separated by commas.
  • The method could declare with throws keyword and decide to not throw also.
example:
class ReThrowTest {
     void f() throws Exception
     {
          try {
               throw new Exception();
          }
          catch(Exception e) {
               System.out.println("Handled paritally in f()");
               throw e;
          }
     }

     void g()
     {
          try {
               f();
          }
          catch(Exception e) {
               System.out.println("Handled completely in g()");
          }
     }

     public static void main(String[] args) { 
          new ReThrowTest().g();
     }
}

However, the exception used with throws keyword should match the exception that is being thrown using the throw keyword.

----------------------------------------------------------------------------------------------------
'finally' block:

  • Always executed if exists, irrespective of exception catch or not.
  • Only one finally block.
  • if catch blocks exists, then finally follows only after the catch block/blocks
  • if no catch block, finally block can follow immediately after try
  • no Finally block after try catch or try is also legal

----------------------------------------------------------------------------------------------------
'try', with resources, the resources need to implement java.lang.Autocloseable interface:(which has a single method close()):
Example :
class TryWithResourcesTest1 {
public static void main(String args[]) throws Exception {
try {
       try (MyResource mr = new MyResource()) {
              System.out.println("Throwing from try block");
              throw new Exception("try block");   ---(*)
       }
}
catch(Exception e) {
       System.out.println(e);
       Throwable[] t = e.getSuppressed();
       System.out.println("Suppressed exception...");
       for(int i=0;i<t.length;i++)
              System.out.println(t[i]);
       }
}
}

class MyResource implements AutoCloseable {
       public void close() throws Exception {
              System.out.println("Throwing from close()");
              throw new Exception("close()");
       }
}


OUTPUT:
Throwing from try block
Throwing from close()
java.lang.Exception: try block
Suppressed exception...
java.lang.Exception: close()

Before forwarding the exception thrown at  ---(*), to the enclosing catch block, The close() method which needs to get executed at the end of try block thats which an implementation of the MyResource, that was created with try, gets supressed. Do note that the method gets executed, but no exception thrown from this method gets caught. It gets suppressed as there's another exception thrown from try, which leaves that try block partially executed.

Hence, the close() method, though still gets executed, but any exceptions in it can be caught, using the ,  Throwable[] t = e.getSuppressed(); as shown in the code above.

________________________________________________________
'Nested try-catch':

A try-block can contain another try-catch sequence.
A catch block can contain another try-catch sequence too.
A finally block can have try-catch blocks(multiple) in it.

________________________________________________________
'custom Exception classes':

A custom Excpetion class can be created in 2 ways:
1) Extend Throwable class
2) Extend any of Thowable's subclass such as Exception


___________________________________________________________________________

No comments:

Post a Comment