Java J2ME JSP J2EE Servlet Android

Java by Example: Exception Handling, creating custom exception class

All related Posts
Java by Example: Exception Handling, creating custom exception class
Java by Example: Exception handling – throw custom Exception
Java By Example: Exception Handling – Throwing exception from method
Java by Example: Exception handling – Basic Exception Handling example ‘try catch’
Java by Example: Exception Handling – Java Exception Basics


You can easily create your own Exception Class where you can put your own exception. To do this what you have to do is just you have create an subclass of java.lang.Exception class.

Here is a basic example of creating custom exception class

package example.java.lang;

public
class
ExceptionExp5
extends Exception{

    public ExceptionExp5() {

        super("[ MY EXCEPTION ] ");

    }

    public ExceptionExp5(String exceptionString) {

        super("[ MY EXCEPTION ] "+exceptionString);

    }

    

    public
static
void main(String args[]){

        try{

            new
ExceptionExp5().tryCustomException();

        }catch(Exception e){

            e.printStackTrace();

        }

    }

    public
void tryCustomException() throws Exception{

        int fibs[]={1,2,3,5,8,10,13};

        for(int i=0;i<fibs.length;i++){

            if(isFibs(fibs[i]))

                System.out.println(fibs[i]+" - OK");

            else

                throw
new
ExceptionExp5(
"Invalid fibonacci number "+fibs[i]);

        }

    }

    private
boolean isFibs(int num){

        int f0 = 1;

        int f1 = 1;

        int fib = 1;

        while(num>=fib){

            if(num==fib)

                return
true;

            fib = f0 + f1;

            f0 = f1;

            f1 = fib;

        }

        return
false;

    }

}

If you execute this you'll get output like..

1 - OK

2 - OK

3 - OK

5 - OK

8 - OK

example.java.lang.ExceptionExp5: [ MY EXCEPTION ] Invalid fibonacci number 10

    at example.java.lang.ExceptionExp5.tryCustomException(ExceptionExp5.java:23)

    at example.java.lang.ExceptionExp5.main(ExceptionExp5.java:12)