Throw Keyword Simplified in Java



Exceptions occur when some predefined exceptional events occur in a program. Sometimes it is ok to handle with predefined Exceptions but sometimes it is reasonable and convenient to define our own Exceptional events. The throw keyword is used to create our own and new Exception which can be thrown to the catch block.In java,throw keyword is used by which the user can throw an exception of his/her own,instead of the automatic Exception object generated by java during runtime.

Below steps happens when we throw an exception:

  1. The Exception object itself is created , in the same way that any java object is created on the heap with new keyword.In general it is not there under normal program execution and the constructor is called for that object.The object is returned from that method.
  2. The current path of the Execution (the original one that was not continued) is stopped and the handle for the Exception object is ejected from the current context.
  3. At this point the Exception handling mechanism takes over and begins to look for an appropriate place is the Exception handler,whose job is to resolve from the issue.
  4. by throwing we can send information about the issue into a larger context by creating an object representing our information and throwing it out of our current context. This is called throwing an Exception.
  5. This throws the Exception allows us in the current context,abdicate responsibilities and  it is handled somewhere else.
Once we throw the handle of the Exception,all further catch clauses for the same try block are ignored and throw causes the Exception to go to next higher context for handling.In addition every information about the Exception is preserved.So that the handle at higher context that catches the specific Exception type can Extract all information from the Object.
The syntax is :

Exception e =new Exception();
throw e;
//e is new Throwable subclass
 
Any object of type throwable can be thrown.Exceptions also accept a message for themselves.

throw new Exceptioon("Here is my Message");
 
Having Exceptions with custom message increases the readability of the application. It also helps in debugging.
Rethrowing an Exception:
It is also possible to rethrow an Exception if we want that we just caught using catch block.As in the catch block,we simply have the handle of the current Exception,we can rethrow.

catch(Exception e)
           {
               System.out.println("An error has occured");
               throw e;
           }
 
An example of throw:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
}
 
The above code will throw an Exception if the divisor is zero.

How user can generate his own Exception using throw:

public static void main(String args[])
{
try{
myDemo();
}
catch(Exception e)
{
System.out.println("Exception thrown by MyDemo is caught here");
}
static void MyDemo()
{
try{
throw new InterruptedException("An Interrupted Exception Occurred");
}
catch(InterruptedException e)
{
throw e;
}
}

Pure user defined Exception:
Beside regular java Exceptions we can create our own Exception called custom exception. They make the code flexible and manageable.
we need to create an Exception class:

public class MyDivisionException Extends Exception
{
//create a parameterized constructor
public MyDivisionException(String message)
{
super(message);
}
}
then the below code:

public static void divide(int x,int y){
try{
if(y==0)
throw new Exception("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
catch(Exception e)
{
}
}
 
can be modified as as:

public static void divide(int x,int y) throws MyDivisionException{ 
if(y==0)
throw new MyDivisionException("The divisor can not be zero")
else
int z=x/y;
System.out.println("The output is"+z);
}
 
How rethrow of Exception preserve the information about the Exception:
If we rethrow the current Exception,the information about the Exception is preserved i.e the origin of the Exception instead of the place where we rethrown it.If we want to know the new stack trace information we can use fillInStackTrace() which returns an Exception object that is created with old Exception by appending the current stack information.

public class MyRethrowExample{
     public static void main(String []args) throws Throwable{
        try{
            methodOne();
        } 
        catch(Exception e)
        {
            System.out.println("Caught in main()");
            e.printStackTrace();
         }
    }
    public static void methodOne() throws Throwable{
        try{
            methodTwo();
        }
        catch(Exception e)
        {
             System.out.println("Caught in methodOne()");
             e.printStackTrace();
            // e.fillInStackTrace();
             throw e;
        }    
    }
    public static void methodTwo() throws Exception{
             System.out.println("Originating at methodTwo()");
             throw new Exception("Thrown from methodTwo()");
     }
 }
 
output of the code:
$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:27)
at MyRethrowExample.methodOne(MyRethrowExample.java:15)
at MyRethrowExample.main(MyRethrowExample.java:5)
Explanation:
the stack trace always remembers it's original point of origin, no matter how many times the Exception is rethrown.

Once we enable the e.fillInStackTrace(); the output is :

$javac MyRethrowExample.java
$java -Xmx128M -Xms16M MyRethrowExample
Originating at methodTwo()
Caught in methodOne()
Caught in main()
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodTwo(MyRethrowExample.java:26)
at MyRethrowExample.methodOne(MyRethrowExample.java:14)
at MyRethrowExample.main(MyRethrowExample.java:4)
java.lang.Exception: Thrown from methodTwo()
at MyRethrowExample.methodOne(MyRethrowExample.java:20)
at MyRethrowExample.main(MyRethrowExample.java:4)
Explanation:
Because of fillInStackTrace() , new point of origin of Exception,The class Throwable must appear in the Exception specification for methodOne() and main().fillInStackTrace() produces handles to a throwable object .throwable  is the base class of Exception but it may so happen that we may get an object that is throwable but not an Exception,so the handler of Exception in main() may miss it.To make sure everything is in order,the compiler forces an Exception specification for throwable.



Throw Keyword Simplified in Java Throw Keyword Simplified in Java Reviewed by Animesh Chatterjee on October 01, 2018 Rating: 5

No comments:

Powered by Blogger.