Exception Handling - throw keyword

Exception Handling - throw keyword
Throw Keyword

Before going to know about throw keyword we need to know how default exception handling takes place. We already know that if there is a run time exception and if its not handled then the default exception handler is responsible for handling the exception.

lets take a class which raises runtime exception
package com.learning.exceptionhandling;

public class SampleClass {

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

We already know division by zero will raise ArithmeticException so the output is the following

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:6)

So now we have question in our mind, who raised the arithmetic exception and how come the default exception handler know that it is Arithmetic Exception? the answer is in front us which is as below,
at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:6)
the method SampleClass.main raised exception.

So in java, methods are responsible for creating the the type of exception object and give it to the JVM, then JVM redirects to the default exception handler to handle the exception.

Now if you don't want method to create an exception object instead we want to create it explicitly then we will go for throw keyword.

lets take a class and lets raise an exception explicitly using throw keyword

package com.learning.exceptionhandling;

public class SampleClass {

 public static void main(String[] args) {
  throw new ArithmeticException("creating an exception object explicitly");
 }

}

output:
Exception in thread "main" java.lang.ArithmeticException: creating an exception object explicitly
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:6)

There are many real time requirements where we need to raise explicit exception object through throws key word.

For example: If you try to login to facebook without providing valid credentials, facebook won't  allow us to login and gives you the exception message, please provide valid credentials.

lets do a simple program which throws an exception if on providing wrong password.

package com.learning.exceptionhandling;

public class SampleClass {

 public static void main(String[] args) throws Exception {
  String userName = "brkopensource";
  String password = "brk123";
  if (userName.equals("brkopensource") && password.equals("brk123")) {
   System.out.println("you have sucessfully Logged in");
  } else {
      throw new Exception("Invalid Credentials, Password should be brk123 but you have entered " + password);  }
 }

}

in the below, example in the if condition if we are checking the username and password is matched then the statement
System.out.println("you have sucessfully Logged in");
will be executed or we will explicitly throw the exception
throw new Exception("Invalid Credentials, Password should be brk123 but you have entered " + password);

lets run the code in two cases

case 1: valid credentials
i.e,  the values of user name and password are as below  

String userName = "brkopensource";
String password = "brk123";

Output:
you have sucessfully Logged in

case 2: invalid credentials,

String userName = "brkopensource";
String password = "brk1323";
Exception in thread "main" java.lang.Exception: Invalid Credentials, Password should be brk123 but you have entered brk3123
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:11)

since the if condition failed, we have explicitly raised an exception object of class java.lang.exception, with the description saying you entered wrong password.

Rules on using throw keyword:

1.  throws keyword can throw only throwable object. i.e, we can explicitly raise an object of the class only if its root class is java.lang.Throwable. We cannot throw objects of the class which is of the root java.lang.Object

lets take a class and lets try to use throw keyword for throwing an object which root class is Object class
package com.learning.exceptionhandling;

public class SampleClass {

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

below code will give compile time error saying
No exception of type SampleClass can be thrown; an exception type must be a subclass of Throwable

lets take a class and lets try to use throw keyword for throwing an object where the root class is Throwable class

package com.learning.exceptionhandling;

public class SampleClass extends Exception {

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

In the above class i have extended the class with Exception class, Exception class is the child of Throwable class, So now if you run the code, it will execute successfully and throw the exception as below
Exception in thread "main" com.learning.exceptionhandling.SampleClass
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:6)

2. Since the program will be terminated when throw keyword encountered in the flow of execution of the code, so we cannot write statements next to throw statements.

package com.learning.exceptionhandling;

public class SampleClass extends Exception {

 public static void main(String[] args) throws SampleClass {
  throw new SampleClass();
  System.out.println("Hello World");
  System.out.println("I am bharani Ravi Kanth");

 }
}

from the above class the statements
System.out.println("Hello World");
System.out.println("I am bharani Ravi Kanth");
will never be executed, so we will get a compile time error saying "Unreachable code".

3. When we are throwing exception object, the object should be always initialized properly before throwing an exception, if we throw null reference of the exception object, throw keyword will throw NullPointerException

lets take a class and lets throw an exception will null reference

package com.learning.exceptionhandling;

public class SampleClass {

 static IllegalArgumentException illegal;

 public static void main(String[] args) throws IllegalArgumentException {
  throw illegal;
 }
}

In the above we created only the IllegalArgumentException static reference but didn't initialize it. and we already know by default the values of static is null. so if we throw IllegalArgumentException reference, we get the below output

Exception in thread "main" java.lang.NullPointerException
 at com.learning.exceptionhandling.SampleClass.main(SampleClass.java:8)

lets take a class and lets throw an exception after initialization exception class object

package com.learning.exceptionhandling;

public class SampleClass {

 static IllegalArgumentException e=new IllegalArgumentException();

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

In the above class we initialized the object for the  IllegalArgumentException class. we get the below output

 Exception in thread "main" java.lang.IllegalArgumentException
 at com.learning.exceptionhandling.SampleClass.(SampleClass.java:5)