Custom Exception is user-defined exception. It is used to customize the exception according to the user requirement. Here In step one we have defined own exception . In step second Using the custome defined exception extends "Exception" class and I have created a class to display numbers 1 to 5 and then throw our MyException. In the below code example I have clearly described "How to use Custom Exception in android".
Step(1).custom defined exception
public class MyException extends Exception
{
    public MyException(String message)
    {
        super(message);
    }
}
Step (2). Using here custom defined exception-
public class ExceptionTest
{
    public static void main(String args[]) throws Exception
    {
        ExceptionTest exceptionTest = new ExceptionTest();
        exceptionTest.displayNumbers();
    }
 
    public void displayNumbers() throws MyException
    {
        for(int i=0;i<10;i++)
        {
            System.out.println("i= "+i);
            if(i==5)
            {
              throw new MyException("My Exception Occurred");
            }
        }
    }
}
 
                       
                    
0 Comment(s)