Java Custom Exception
Java Custom Exception
Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java throw keyword is used to throw the Java Custom Exception. One can throw a checked as well as an unchecked custom exception.
Throwing a Custom Checked Exception
For creating a custom-checked exception, the Java Exception class must be extended. The custom-checked exception is detected at the compile time. The following program illustrates how one can raise a custom-checked exception.
FileName: CustomCheckException.java
class NoProperNameException extends Exception { // constructor of the class NoProperNameException NoProperNameException(String m) { // invoking the constructor of the Exception class // to display the desired message super(m); } } public class CustomCheckException { private String stuName; private int stuAge; // a method for checking the string s contains any letter other than small letter or not public boolean containsAlphabet(String s) { // size of the string s int size = s.length(); // iterating over the characters of the string s for (int i = 0; i < size; i++) { char c = s.charAt(i); if (!(c >= 'a' && c <= 'z')) { // we found a letter which not within range of a to z (all small letters) return false; } } return true; } // declaring that the constructor may throw the NoProperNameException public CustomCheckException(int age, String name) throws NoProperNameException { if(!containsAlphabet(name) && name != null) { // the string name contains at least one letter, which is not a small letter String str = "The name should be proper (Should only contain characters ranging from a to z (all small))"; NoProperNameException obj = new NoProperNameException(str); throw obj; } this.stuName = name; this.stuAge = age; } // method for displaying the name and age of student public void display() { System.out.println("The Student's name is: "+ this.stuName); System.out.println("The Student's age is: "+ this.stuAge); } // main method public static void main(String argvs[]) { String names[] = {"amit", "Sumit"}; int ages[] = {34, 44}; // calculating size of the names array int size = names.length; for(int i = 0 ; i < size; i++) { // try-catch block for handling any custom exception try { // instantiating the class CustomCheckException CustomCheckException obj = new CustomCheckException(ages[i], names[i]); // method's name obj.display(); } catch(NoProperNameException expn) { System.out.println("In the catch block " + expn); } } } }
Output:
The Student's name is: amit The Student's age is: 34 In the catch block NoProperNameException: The name should be proper (Should only contain characters ranging from a to z (all small))
Explanation:The above program is written in such a way that it only raises the custom exception when anything other than a small letter is passed.The second string of the array names contains a capital letter ‘S’, and because of it, the custom exception is raised for the second string “Sumit”.
Throwing a Custom Un-Checked Exception
Un-checked exceptions are those exceptions that are checked at the runtime. To throw an un-checked exception, the class RuntimeException must be extended. Let’s observe the following program for a better understanding.
FileName: CustomCheckException1.java
class NoCompileTimeException extends RuntimeException { // constructor of the class NoCompileTimeException NoCompileTimeException(String m) { // invoking the constructor of the Exception class // to display the desired message super(m); } } public class CustomCheckException1 { // a method for checking whether the number n is greater than 20 or not public boolean isGreaterThanTwenty(int n) { if(n > 20) { return true; } return false; } // declaring that the constructor may throw the NoCompileTimeException public CustomCheckException1(int N) throws NoCompileTimeException { if(isGreaterThanTwenty(N)) { // the string name contains at least one letter, which is not a small letter String str = "The numbers should be either less than or greater than 20"; NoCompileTimeException obj = new NoCompileTimeException(str); throw obj; } } // method for displaying the numbers public void display(int n) { System.out.println("The num: "+ n + " is the valid number"); } // main method public static void main(String argvs[]) { // input array that contains only numbers int numArr[] = {34, 44, 1, 7, 9, 0, 67, 34, 2, 71}; // calculating size of the numArr array int size = numArr.length; // iterating over numbr array for(int i = 0 ; i < size; i++) { // try-catch block for handling any custom exception try { // instantiating the class CustomCheckException1 CustomCheckException1 obj = new CustomCheckException1(numArr[i]); // invoking the method display() // only gets invoked when there is no exception raised in the try block obj.display(numArr[i]); } catch(NoCompileTimeException expn) { System.out.println("In the catch block " + expn); } } } }
Output:
In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20 In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20 The num: 1 is the valid number The num: 7 is the valid number The num: 9 is the valid number The num: 0 is the valid number In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20 In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20 The num: 2 is the valid number In the catch block NoCompileTimeException: The numbers should be either less than or greater than 20
Explanation: The above program throws the exceptions when it encounters a number greater than 20.