Throw and Throws keyword in Java.


In interview room most probably asking the question.

Throw keyword:

First, Forget about java all this thing For example Suppose I want to throw then someone going to catch. assume that here it's a ball game. and I throw the ball to catch someone person, were in java the person who throw the ball is the programmer and the other person catching that exception by JVM for that throw keyword is required. where which is throwable type is only thrown the exception, no other object or class you may throw.

Look like..

Let us explain with an example.

class Test{
        public static void main(String args[]){
              System.out.println(10/0);
       }
}

exception in thread main java.lang.arithmaticException / by zero
at Test.main()

In this case, which is the responsible for exception arise. JVM, JVM is responsible for exception handling. it's responsible internally automatically by JVM.
By , we want to create and handle exception explicitly that so we want to use throw keyword. we want to hand our exception to JVM manually.
class Test{
        public static void main(String args[]){
              throw new ArithmaicException("/ by zero explicitly");
       }
}

exception in thread main java.lang.arithmaticException / by zero explicitly
at Test.main()

were new ArithmaicException("/ by zero explicitly"); means a creation of ArithmaicException object explicitly. and throw is hand our exception object to the JVM manually.
 
In many cases in that. suppose one example
class Test{
        static ArithmaticException ae = new ArithmaticException();
        public static void main(String args[]){
              throw ae;
       }
}

exception in thread main java.lang.arithmaticException
at Test.main();

But,

class Test{
        static ArithmaticException ae; // you no any create an object and it's null
        public static void main(String args[]){
              throw ae;//throw as null 
       }
}

runtime : exception in thread main NullPointerException

Throws Keyword:

We can use Throws keyword to delegate responsible for exception handling to a caller(It may be the other method or JVM), then caller method is responsible for to handle that exception. it requires only for check exception and use of throws keyword for unchecked exception there is no impact.suppose one example.

class Test{
     public static void main(String args[])throws InteruptedException
     {
                     Thread.sleep(10000);   
     }
}
above Test class complile fine, and run successfully. but if you won't use throws statement then the program not compile. for ex.
class Test{
     public static void main(String args[])
     {
                     Thread.sleep(10000);   
     }
}
comile time error: unreported exception java.lang.InteruptedException.

so, there is simple thing about throw and throws keyword.

Comments