throw keyword - rahul00773/JavaConcepts GitHub Wiki

throw Keyword in java

Sometimes we can create exception objects explicitly and we can handover JVM manually. For this, we have to use throw keyword.

throw new ArthmeticExceoption("/ by zero"); /// creation of aithmeticexception object explicitly // throw keyword is used for handover our created exception object to the jvm manually

Hence the main objective of the throw keyword is to handover our created exception object to the JVM manually.

Hence the result of the following two programs is exactly the same:

class Test

public static void main(String[] args){

System.out.print(10/0);

}

In this case main method is responsible exception object and handover to jvm

class Test

public static void main(String[] args){

throw new ArthmeticExceoption("/ by zero");

}

Run time exception will come in both cases:

Exception in thred "main": java.lang.ArthmeticException: / by zero at Test.main()

In this case, the programmer creating an exception object explicitly and handovers to the JVM manually.

Note: Best use of the throw keyword is for user-defined exceptions or customized exception.

Case1:

throw e;

If e refers null then we will get a null pointer exception.

class Test{

static AE e= new AE();

public static void main(String[] args){

throw e; }

} // Aithmetic exception will come

class Test{

static AE e;

public static void main(String[] args){

throw e;

} } // Null pointer exception will come

}

Case2: After throw statements, we are not allowed to write any statement directly. Otherwise, we will get a compile-time error saying Unreachable statement.

class Test{

public static void main(String[] args){

System.out.println(10/0); System.out.println("hello");

}

} // Run Time arthmetic exception will come

class Test{

public static void main(String[] args){

throw new AirthmeticException("/ by zero"); System.out.println("hello");

}

} // Compile time error will come saying the unreachable statement

Case3: We can use the throw keyword only for throwable types. If we are trying to use for normal java objects we will get compile-time error saying Incomapitble types.

class Test{

public static void main(String[] args){

throw new Test();

} // compile time error: Incompatible type found : Test required Java.lang.Throwable();

class Test extends RuntimeException {

public static void main(String[] args){

throw new Test();

} // Runtime Exception : Exception in thread "main" Test at testmain();