Custom Exceptions in Java

Java itself has so many exceptions predefined .If we need to create our own exceptions based on our requirement , Java provides options for that. here we are going to discuss about Custom Exceptions in Java.

Custom Exceptions in Java

  Custom Exceptions in Java are exceptions defined by programmer. It is easy to create  new exception type in Java. Create a new class by extending the Exception class . The concept  is explained with an  example.

public class NegetiveNumberException extends Exception {
public NegetiveNumberException(){
super();
System.err.println("Negative Number found");
}
}

Now let us see the main class.It simply throws s a NegetiveNumberException when the integer count reaches -1.

public class Sample {
public Sample() {
}
public void getException() throws NegetiveNumberException {
int count = 100;
while (count >= −1) {
if (count < 0) { throw new NegetiveNumberException(); } count−−; } } public static void main(String[] args) { Sample sample = new Sample(); try { sample.getException(); } catch (NegetiveNumberException e) { e.printStackTrace(); } } }

Now let us see the output.

Output

com.exception.NegetiveNumberException

    at com.exception.Sample.getException(Sample.java:17)

    at com.exception.Sample.main(Sample.java:26)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

    at java.lang.reflect.Method.invoke(Method.java:601)

Leave a Reply

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