1.To create our own Exception class in java we need to extend our ExceptionClass to "Exception" class.
2.Create any of the constrctors given by (http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html) Exception of the class.
3. Use throw keyword to throw exception.(new MyExceptionClass("My Exception Occurred"))
In this example i have created MyExceptionClass which extends Exception class.
class MyExceptionClass extends Exception
{
public MyExceptionClass(String message) // Constructor
{
super(message);
}
}
public class CustomExceptionExample
{
public static void main(String args[]) throws Exception
{
CustomExceptionExample exceptionExample = new CustomExceptionExample();
exceptionExample.displayNumbers();
}
void displayNumbers() throws MyExceptionClass //throws our customized exception.
{
for(int i=0;i<10 br="" i="" nbsp="">{
System.out.println("i= "+i);
if(i==3)
{
/*
Throw keyword is used to throw the exception manually. It is mainly used when the program fails
to satisfy the given condition and it wants to warn the application
*/10>
{
public static void main(String args[]) throws Exception
{
CustomExceptionExample exceptionExample = new CustomExceptionExample();
exceptionExample.displayNumbers();
}
void displayNumbers() throws MyExceptionClass //throws our customized exception.
{
for(int i=0;i<10 br="" i="" nbsp="">{
System.out.println("i= "+i);
if(i==3)
{
/*
Throw keyword is used to throw the exception manually. It is mainly used when the program fails
to satisfy the given condition and it wants to warn the application
*/10>
throw new MyExceptionClass("My Exception Occurred");
}
}
}
}
}
}
}
}
output:
i= 0
i= 1
i= 2
i= 3
Exception in thread "main" MyExceptionClass: My Exception Occurred
at CustomExceptionExample.displayNumbers(CustomExceptionExample.java:32)
at CustomExceptionExample.main(CustomExceptionExample.java:15)
i= 1
i= 2
i= 3
Exception in thread "main" MyExceptionClass: My Exception Occurred
at CustomExceptionExample.displayNumbers(CustomExceptionExample.java:32)
at CustomExceptionExample.main(CustomExceptionExample.java:15)