Create your own exception class in java

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
*/
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)

Search This Blog

All the rights are reserved to this blog is belongs to me only.. Powered by Blogger.