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(){
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.



    at com.exception.Sample.getException(

    at com.exception.Sample.main(

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

    at sun.reflect.NativeMethodAccessorImpl.invoke(

    at sun.reflect.DelegatingMethodAccessorImpl.invoke(

    at java.lang.reflect.Method.invoke(

Tagged with 

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">