Example & Tutorial understanding programming in easy ways.

What is throw keyword?

The throw keyword is mostly used to throw the exception to raise user defined exception

 i.e  if user define its own exception by extending the exception class, then that exception can be raise by only using throw keyword.

Throw keyword should be defined in either try catch block or the method should be defined using throws keyword. Here is an example :

//Example to demonstrate throw

class ThrowDemo
{
    static void play()  
    {
        try
        {    
            System.out.println("before");
            throw new IllegalAccessException("demo");
            //System.out.println("after");
        }
        catch(Exception e)
        {    
            System.out.println("Exception e"+e);
        }
    }
    public static void main(String args[]) throws Exception
    {
        play();
    }
}

Read More →