Throw and throws keywords

Throw and throws keywords

throw keyword:

throw keyword in java. 

  Sometime we can create exception object explicitly, we can handover to the JVM manually. For this we have to use throw keyword.
 
throw new ArithmeticException("/ by zero");
where,
        throw : handover our created exception object to the JVM manually.
        new AE("/ by zero") : Creation of AE object explicitly.
 
     For this purpose we use throw keyword. Hence the main objective of throw keyword is to hand over our created exception object to the JVM manually.
 
Hence the result of following programs are same.
 
throw keyword used in java

  • In thirst case main() is responsible to create exception object and handover to the JVM.
  • In second case programmer creating exception object explicitly and handover to the JVM manually.

Best use of throw keyword is for user define exception or customized exceptions.

Case 1:

 throw e :

If e refers null then we will get NullPointerException

 Ex1:
 
class Test
{
    static ArithmeticException e = new ArithmeticException ();
    public static void main(Srting[] s)
    {
          throw e;
    }
}
  RE:    Exception in thread "main" java.lang.ArithmeticException
    at com.test.Test.<clinit>(Test.java:7)

 
 Ex2:
class Test
{
    static ArithmeticException e ;
    public static void main(Srting[] s)
    {
          throw e;
    }
}
  RE:    Exception in thread "main" java.lang.NullPointerException
    at com.test.Test.main(Test.java:11)
 

Case 2:      

After throw statement we are not allowed to write any statement directly, otherwise we will get compile time error saying: unreachable statement.
 
Ex1:
public class Test {

    static ArithmeticException e ;
    
    public static void main(String[] args) {
        System.out.println(  10/0 );
        System.out.println("Raka"); 
    }
}
 RE:    Exception in thread "main" java.lang.ArithmeticException
    at com.test.Test.<clinit>(Test.java:7)
 
 
Ex2:
public class Test {       
    public static void main(String[] args) {
        throw new ArithmeticException("/ by zero");
        System.out.println("Raka");  // CE: Unreachable code
    }
}

Case 3: 

We can use throw keyword only for throwable types. If we are trying to use for normal java objects, we will get compile time error saying: incompatible types
 
Ex1:
  class Test
  {
     public static void main(String[] s)
     {
        throw new Test();
     }
  } 
 CE: No exception of type Test can be thrown; an exception type must be a subclass of    Throwable
Ex2:
  class Test extends RuntimeException
  {
     public static void main(String[] s)
     {
        throw new Test();
     }
  } 
 CE:   Exception in thread "main" com.test.Test
           at com.test.Test.main(Test.java:11)

 

throws keyword:

 In our program if there is possibility of raising checked exception then compulsory we shoudl handle the checked exception. Otherwise we will get compile time error saying:-

unsupported exception xxx, must be caught or declared to be thrown.

Ex1:

class Test
{
    public static void main(String[] s)
   {
       Thread.sleep(1000);
   }
}
CE:Unhandled exception type InterruptedException
 
 We can handle this compile time error by following 2 ways.
  • By using try-catch 
Ex:
try{
   thread.sleep(1000);
}
catch(Exception e){
}
  • By using throws keyword
 We can use throws keyword to delegate responsibility of exception handling to the caller ( it may be another method or JVM ) then caller method is responsible to handle that exception.
 
Ex:
 
class Test
{
   public static void main(String[] s)  throws InterruptedException
  {
    Thread.sleep(1000);
  }
 
  • Throws keyword required only for checked exceptions and uses of throws keyword for unchecked exception, there is no use or impact.  
  • Throws keyword required only to convince compiler and uses of throws keyword does not prevent abnormal termination of the program.
 
throws keyword in java

  •  If remove at least one throws statement that can code would not compile ( in above program ).

throws clause:

  1. We can use to delegate responsibilities of exception handling to the caller  ( it may be method or JVM )
  2. It is required only for checked exception and uses of throws keyword for unchecked exception there is no impact.
  3. It is required only to convince compiler and uses of throws does not prevent abnormal termination of program.
It is recommended to use try-catch over throws keyword.

Case 1: 

We can use throws keyword for methods and constructors but not for classes.
throws keyword in java

Case 2: 

We can use throws keyword only for Throwable types. If we are trying to use for normal java classes then we will get compile time error: In compatible type
 
Ex 1:
 
class Test
{
  public void m1() throws Test
  {
  }

 CE: No exception of type Test can be thrown; an exception type must be a subclass of Throwable
Ex 2:
class Test extends RuntimeException
{
  public void m1() throws Test
  {
  }
 O/P: successfully compile
 

Case 3:

Ex 1:

class Test
{
    public static void main(String[] agrs)
   {
         throw new Exception();
   }
 
CE: Unhandled exception type Exception 
 
Ex 2:
 public class Test 
{
    public static void main(String[] args) {
         throw new Error();
    } 
}
 
RE: Exception in thread "main" java.lang.Error
    at com.test.Test.main(Test.java:7)
 

Case 4:

Within the try block if there is no chance of rising an exception, then we cannot write catch block for that exception otherwise we will get compile time error saying: 
 
Exception xxx is never thrown in body of corresponding try statement.
 
 But this rule is applicable only for fully checked exception.
 
Ex 1:
 
class Test
{
  public static void main(String[] agrs)
  {
      try{
          System.out.println("Raka");
      }
      catch(ArithmeticException ae)  // Unchecked exception
      {
 
      }
  }
}  
 O/P: Raka
 
 Ex 2:
 
class Test
{
    public static void main(String[] agrs)
    {
       
          try{ 
                  System.out.println("Raka");
          } 
          catch(Exception ae)  // Partially Unchecked exception
         { 
         }
    }
O/P: Raka 
 
Ex 3:
 
class Test
{
    public static void main(String[] agrs)
    {
       
          try{ 
                  System.out.println("Raka");
          } 
          catch(IOException ae)  // Fully Unchecked exception
         { 
         }
    }
}
 
 CE: Unreachable catch block for IOException. This exception is never thrown from the try statement body
 
Ex 4:
 
class Test
{
    public static void main(String[] agrs)
    {
       
          try{ 
                  System.out.println("Raka");
          } 
          catch(Error ae)  // Unchecked exception
         { 
         }
    }
      }  
 
O/P: Raka 
 
 
 
RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

Post a Comment (0)
Previous Post Next Post