Example & Tutorial understanding programming in easy ways.

How to create custom Exception?

Writing your own custom exception in Java. Writing your own exception in java is very simple. All you need to do is just extend "Exception" class.

For example:-

public class MyException extends Exception
{
    public MyException(String message)         
    {  
        super(message);        
    }      
}


Analysis of the above code

"MyException" is our exception class name. You can give any name of your choice.
Important thing to be noted is our class extends "Exception" class. This is all we need to do make a custome defined exception
"Now we define a constructor of my class. This constructer takes a "String" argument. We call super class' constructor(super class here is "Exception class") and pass this string to it. Not java creates a new Exception with the message as in the string passed.

2. Using the custome defined exception

Let's see how we can use the exception "MyException" that we created now. We are going to write a class which will display numbers 1 to 6 and then throw our "MyException"
    
public class ExceptionDemo  
{      
    public static void main(String args[]) throws Exception    
    {          
        ExceptionDemo exceptionDemo = new ExceptionDemo();         
        exceptionDemo.displayNumbers();    
    }      
         
    public void displayNumbers() throws MyException    
    {          
        for(int i=0;i<10;i++)       
        {              
            System.out.println("i= "+i);           
            if(i==6)           
            {                  
              throw new MyException("My Exception Occurred");              
            }          
        }      
    }
}

Read More →