throws exception in java


Contents of page :
  • throws unChecked exception >
  • throws Checked exception >
  • Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-catch block from where call to method m() was made.
  • Program 2 - Throwing Exception from m() method and then again throwing it from calling method [ i.e. main method]



throws is written in method’s definition to indicate that method can throw exception.

throws unChecked exception >
  • We need not to handle unChecked exception either by catching it or throwing it.

Above code throws NullPointerException (unChecked exception) and didn’t handled it from where method m() was called and no compilation error was thrown.


throws Checked exception >
  • We need to handle checked exception either by catching it or throwing it further, if not handled we will face compilation error.

       



Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-catch block from where call to method m() was made.
import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
          try {
                 m();
          } catch (FileNotFoundException e) {
             System.out.println("FileNotFoundException handled in try-catch block");
          }
          System.out.println("after calling m()");
   }
   static void m() throws FileNotFoundException{
         
   }
}
/*OUTPUT
after calling m()
*/
method m() propagated exception to calling method (i.e. main method) using throws.


Program 2 - Throwing Exception from m() method and then again throwing it from calling method [ i.e. main method]
Ultimately exception is not handled properly in this case, but this approach is used in many live projects (i.e. in web applications).
import java.io.FileNotFoundException;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) throws FileNotFoundException {
          m();
          System.out.println("after calling m()");
   }
   static void m() throws FileNotFoundException{

   }
}
/*OUTPUT
after calling m()

*/

method m() propagated exception to calling method (i.e. main method) using throws, and
main propagated exception to JVM using throws.




RELATED LINKS>



eEdit
Must read for you :