- "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 MyException extends Exception
{
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
No comments