We can use throw keyword to handover our created exception object to the JVM explicitly.

Example:1Creating Exception object by main method.

public class ExceptionDemo {
  public static void main(String[] args) {
    System.out.println(10/0);
  }
}
/*
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionDemo.main(ExceptionDemo.java:5)
*/

In the above example,Creation of Exception object and handover that object to the JVM performed internally by main method.

Example:2Creating Exception object by Programmer.

public class ExceptionDemo {

	public static void main(String[] args) {
		
		ArithmeticException ae=new ArithmeticException("/by zero");
		throw ae;
		
	}
}
/* /
Exception in thread "main" java.lang.ArithmeticException: /by zero
	at ExceptionDemo.main(ExceptionDemo.java:5)

*/

In the above example,Creating the Exception object and handover it to the JVM explicitly by the programmer.

case:1

package com.java2learn.exception;
public class ExceptionDemo {

	public static void main(String[] args) {
		
		throw new Test();
	}
}

class Test{
	
}

Output:
Compiletime Error:No exception of type Test can be thrown; an exception type must be a subclass of Throwable

case:2

package com.java2learn.exception;
public class ExceptionDemo {

	public static void main(String[] args) {
		
		throw new Test();
	}
}

class Test extends RuntimeException{
	
}

Output:
Exception in thread “main” com.java2learn.exception.Test
at com.java2learn.exception.ExceptionDemo.main(ExceptionDemo.java:7)

case:3

package com.java2learn.exception;
public class ExceptionDemo {

	static ArithmeticException e = new ArithmeticException("/by zero");
	public static void main(String[] args) {
		
		throw e;
	}
}

Output:
Exception in thread “main” java.lang.ArithmeticException: /by zero
at com.java2learn.exception.ExceptionDemo.(ExceptionDemo.java:5)

Here Explicitly we created a object to the ArithmeticException class and that object was thrown by thow to the JVM.

case:4

package com.java2learn.exception;
public class ExceptionDemo {

	static ArithmeticException e ;
	public static void main(String[] args) {
		
		throw e;
	}
}

Output:
Exception in thread “main” java.lang.NullPointerException
at com.java2learn.exception.ExceptionDemo.main(ExceptionDemo.java:8)

Here we didn’t create Object to the AritmeticException class just we created a reference, so reference variable is not pointing to any object and we thrown only reference variable that’s why only it shows NullPointerException.

Note:After throw keyword we are not allowed to place any statements directly other wise compile time error.

Example:

package com.java2learn.exception;
public class ExceptionDemo {

	public static void main(String[] args) {
		
		throw new  ArithmeticException();
		System.out.println("Next statement after throw keyword.");
	}
}

Output:
Compiletime Error:Unreachable code