Showing posts with label Throws. Show all posts
Showing posts with label Throws. Show all posts

Difference between throw and throws in Java

 

This is one of the famous interview question asked. When we talk about throw and throws it comes under Exception handling in Java and both are keywords used to handle different types of exception in our application. Before knowing about throw and throws needs to know about try, catch and finally blocks in Java and how its used to handle and catch the exception in Java.

Throw is used inside any methods or blocks to throw Exception, but throws used to method declaration specifying that list of Exceptions can be thrown from particular method. Below is a sample code to use throw and throws in Java.


public void myMethod() throws FileNotFoundException, RemoteException {
        ....
        throw new NullPointerException();
}


Suppose if any method throws Exception then caller method needs to handle those Exception or can be re-thrown to previous method call. 


public class ThrowTest {
    
    public static void main(String[] args) {
        try{
            myMethod();
        }catch (FileNotFoundException e) {
            // TODO: handle exception
        }catch (RemoteException e) {
            // TODO: handle exception
        }
    }
    
    public static void myMethod() throws FileNotFoundException, RemoteException {
        //....
        throw new NullPointerException();
    }
}


(OR)


public class ThrowTest {
    
    public static void main(String[] args) throws FileNotFoundException, RemoteException {
        myMethod();        
    }
    
    public static void myMethod() throws FileNotFoundException, RemoteException {
        //....
        throw new NullPointerException();
    }
}


Throw statement can be used anywhere in the method statements like inside if-else, switch etc., but throws should be always used in method declaration.

While we throw an Exception explicitly control transferred to the called method. 

If we didn't handle throws Exception in caller method then we will compile time error, where as if didn't handle throw Exceptions then there won't be any compile time error. Statements followed by method call will not be executed. 


public class ThrowTest {
    
    public static void main(String[] args)  {
        System.out.println("Before method call...");
        myMethod();        
        System.out.println("After method call...");
    }
    
    public static void myMethod()  {
        System.out.println("Before throw...");
        throw new NullPointerException();
        
        // Unreachable code 
        //System.out.println(\"After throw...\");
    }
}

OUTPUT:


Before method call...
Before throw...
Exception in thread "main" java.lang.NullPointerException