Creating User defined checked and unchecked Exception/ custom Exception in java


Creating user defined checked exception >
class UserDefinedException extends Exception {
   UserDefinedException(String s) {
          super(s);
   }
}
By extending java.lang.Exception, we can create checked exception.



Creating user defined unchecked exception >
class UserDefinedException extends RuntimeException {
   UserDefinedException(String s) {
          super(s);
   }
}
By extending java.lang.RuntimeException, we can create unchecked exception.


Full program for testing user defined checked Exception >
package com.ankit;
/*
* User defined Exception/ custom Exception
*/
class UserDefinedException extends Exception {
   UserDefinedException(String s) {
          super(s);
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com
* Main class */
public class UserDefinedExceptionTest {
   public static void main(String... arg) {
          try {
                 throw new UserDefinedException("user defined exception was thrown "
                                                     + "and handled.");
          } catch (UserDefinedException e) {
                 e.printStackTrace();
          }
   }
}
/*OUTPUT
com.ankit.UserDefinedException: user defined exception was thrown and handled.
   at com.ankit.UserDefinedExceptionTest.main(UserDefinedExceptionTest.java:25)
*/





RELATED LINKS>



eEdit
Must read for you :