Java J2ME JSP J2EE Servlet Android

Java by Example: Exception handling – throw custom Exception

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

Exception indicates illegal operation. So for your program you can define an operation as illegal. Say in your login program you allow maxim 3 times retry with wrong user/password. Then you can define your exception for attempt to login for more than thrice. And if this case occurs you can throw your exception.

Here is an example of throw custom exception to check if a number is a Fibonacci number or not. When a non Fibonacci number found exception 'Invalid fibonacci number' will be thrown..

Here is the example . .

public
class ExceptionExp4 {

    public
static
void main(String args[]){

        ExceptionExp4 excpExp = new ExceptionExp4();

        try{

            excpExp.tryCustomException();

        }catch(Exception ce){

            ce.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 Exception("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;

    }

}


 

Fibonacci number series is

1 2 3 5 8 13 21 34 . . . .

So if you try to execute exception should occur when 10 is found..

Lets see the output of this program...

1 - OK

2 - OK

3 - OK

5 - OK

8 - OK

java.lang.Exception: Invalid fibonacci number 10

    at example.java.lang.ExceptionExp4.tryCustomException(ExceptionExp4.java:18)

    at example.java.lang.ExceptionExp4.main(ExceptionExp4.java:7)


 

So in this way we can easily create our own exception with our own message as per our needs.