• "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 custom defined exception
    "Now we define a constructor of my class. This constructor 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.

    •   public class MyException extends Exception

      {

          public MyException(String message)        

          { 

              super(message);       

          }     

      }
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++)      
            {     
               try{       
                System.out.print(i);          
                if(i==6)          
                {                 
                  throw new MyException("My ExceptionOccurred");             
                }
               catch(Exception e){
              System.out.println(e);
            }    
        }
    }

 

Output: 1 2 3 4 5 6  My exception occured

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu