throw and throws in java

throw:

throw is used in re-throwing exception process or we can say that it is used to throw an exception object explicitly. It can take at most one argument which will be an exception object. Only unchecked exception can be thrown.

Syntax:

throw exceptionObject;

Example

public class Main {
 
   public int reminderTest(int number1, int number2) {
     try{
           return number1/number2;
      }catch(ArithmeticException e){
         throw e; 
      }
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      try{
          System.out.println(main.reminderTest(40, 0));
      }catch(Exception e){
          e.printStackTrace();
      }
   }
 
}

Output

java.lang.ArithmeticException: / by zero
        at Main.reminderTest(Main.java:5)
        at Main.main(Main.java:14)

 

throws:

throws keyword is used to throw an exception object implicitly. The throws keyword is used with the method signature. We can declare more than one type of exceptions with method signature which should be comma separated. Note: 1.     throws is commonly used to throw checked exception. 2.     If we are calling a method that declares an exception then we must have to either caught or declare the exception. 3.     Exception can be re-thrown.

Syntax:

methodName () throws comma separated list of exceptionClassNames{}

Example

public class Main {
 
   public int reminderTest(int number1, int number2) throws ArithmeticException, Exception{
     return number1/number2;
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      try{
          System.out.println(main.reminderTest(40, 0));
      }catch(Exception e){
          e.printStackTrace();
      }
   }
 
}

Output

java.lang.ArithmeticException: / by zero
        at Main.reminderTest(Main.java:4)
        at Main.main(Main.java:10)

 

Difference between throw and throws.

                    throw keyword                     throws keyword
  1. It is used to explicitly throw an exception.
  2. By using throw, only unchecked exception can propagate.
  3. It is Used with in the method body.
  4. Multiple exceptions cannot be thrown using throw keyword.
  1. It is used to implicitly throw an exception.
  2. By using throws, both checked and unchecked exception can propagate.
  3. It is used in method signature.
  4. Multiple exceptions can be declared using throws keyword.

 

Java interview questions on Exception Handling

Please follow and like us:
Content Protection by DMCA.com