Custom Exception

As the name suggests Custom Exception means it is Custom or User Defined Exceptions. User can create his/her own exceptions. 
For this, developer has to extend the existing checked or unchecked exception. Lets see some examples…..
CustomUncheckedException.java
package technical.jungle.com.exception;
public class CustomUncheckedException extends NullPointerException{
CustomCheckedException(String s){
super(s);
}
}
CustomUnCheckedExceptionDemo.java
package technical.jungle.com.exception;

public class CustomUncheckedExceptionDemo { 
 private static String someNullValue = null;

public static void main(String args[]) {  
      validation(someNullValue); 
  }
 
private static void validation(String str) {  
      str = str.toUpperCase();  
      System.out.println(str); 
     }
}

Output:

Exception in thread “main” java.lang.NullPointerException
at technical.jungle.com.exception.CustomUncheckedExceptionDemo.validation(CustomUncheckedExceptionDemo.java:11)
at technical.jungle.com.exception.CustomUncheckedExceptionDemo.main(CustomUncheckedExceptionDemo.java:7)

Some points about above example

  1. CustomUnCheckedException class inherits checked exception, called NullPointerException.
  2. CustomUncheckedExceptionDemo has a string which has value as null. Whenever we try to do some operation on that value then it throws NullPointerException.
  3. Handling on checked or unchecked exceptions will be same.

How to solve above thrown exception
CustomUncheckedException.java class will be same as above.
CustomUncheckedExceptionDemo.java

  1. package technical.jungle.com.exception;
  2. public class CustomUncheckedExceptionDemo {
  3. private static String someNullValue = null;
  4. public static void main(String args[]) {
  5.                 System.out.println(“www.technicaljungle.com”);
  6. try {
  7. validation(someNullValue);
  8. } catch (CustomUncheckedException e) {
  9. System.out
  10. .println(“Catch custom exception CustomUncheckedExceptionDemo”);
  11. }
  12. }
  13. private static void validation(String str) {
  14. if (str == null) {
  15. throw new CustomUncheckedException(someNullValue);
  16. }
  17. System.out.println(“The value is : ” + str);
  18. }
  19. }
Output:

www.technicaljungle.com
Catch custom exception CustomUncheckedExceptionDemo

Some points about above example

  1. CustomUncheckedException class inherits checked exception, called NullPointerException.
  2. CustomUncheckedExceptionDemo has a string which has value as null. So we are checking the value against null. If null then throwing against custom exception.
  3. In the calling method, trying to handle the custom exception.

If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.