Tuesday, February 11, 2020

throws clause exception handling

"throws" clause (Java Exceptiontion Handling)

Java provides five keywords for the exception handling mechanism.

  • try
  • catch
  • throws
  • throw
  • finally 

What does the "throws"  do?

"throws" actually does nothing itself, it just delays the exception handling. Sometimes, a method may cause an exception but does not seek to handle it. This method must specify(mark) this behavior so that callers of these methods may protect themselves against that Exception. While declaring such a method programmer has to specify which exception this method may throw using “throws” keyword. Multiple Exceptions may be added using a comma-separated list.
Any method that uses an exception throwing method with "throws" keyword will have to either handle this exception or throw(mandatory) this exception as well. If the main() method is using this method and not handling exception thrown by this method, the Java runtime will handle the exception itself.
 For example,

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

class A{
      public void testThrows() throws IOException //throwing exception
      {//Any method using testThrows() will have to
            //either handle this exception or
            //must throw this exception
            FileOutputStream f=new FileOutputStream("message.txt");
            BufferedOutputStream bos=new BufferedOutputStream(f);
            String message="Welcome to java";
            byte[] b=message.getBytes();
            bos.write(b);
            System.out.println("Message written successfully");
      }
}
public class ExceptionDemo {

      public static void main(String[] args) {
            A a=new A(); //main() method must handle
            try {//Exception here or throw it
                  a.testThrows();
            } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
      }

}

Rules of "throws" (Overriding method)

  • The overriding method must NOT throw checked Exceptions that are new or broader than those declared by the overridden method.
  • For example, A method throwing SQLException can not be overridden by a method throwing IOException or ANY other Exception unless the Exception is a subclass of SQLException class.
  • Or, A method declared in Superclass A throwing Exception X if overridden in Subclass B can only throw either X as Exception or Any Exception Subclass of X.
  • throws in java
    throws clause
  • This rule is applicable only for checked Exceptions, not for unchecked exceptions.

Video Tutorial