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;
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
- CustomUnCheckedException class inherits checked exception, called NullPointerException.
- CustomUncheckedExceptionDemo has a string which has value as null. Whenever we try to do some operation on that value then it throws NullPointerException.
- 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
- package technical.jungle.com.exception;
- public class CustomUncheckedExceptionDemo {
- private static String someNullValue = null;
- public static void main(String args[]) {
- System.out.println(“www.technicaljungle.com”);
- try {
- validation(someNullValue);
- } catch (CustomUncheckedException e) {
- System.out
- .println(“Catch custom exception CustomUncheckedExceptionDemo”);
- }
- }
- private static void validation(String str) {
- if (str == null) {
- throw new CustomUncheckedException(someNullValue);
- }
- System.out.println(“The value is : ” + str);
- }
- }
Output:
www.technicaljungle.com
Catch custom exception CustomUncheckedExceptionDemo
Catch custom exception CustomUncheckedExceptionDemo
Some points about above example
- CustomUncheckedException class inherits checked exception, called NullPointerException.
- CustomUncheckedExceptionDemo has a string which has value as null. So we are checking the value against null. If null then throwing against custom exception.
- In the calling method, trying to handle the custom exception.