Custom exceptions are created to represent some of the error types of your application, providing new meaning for one or more of the problems that your code may occur.
You can differentiate one or more errors that may occur when the code is running, or give specific meaning to a set of errors in your application.
Custom exception classes need to inherit exception
public class Myselfexception extends Exception {
private int detail;
public myselfexception (int index) {
Detail=index;
}
Public String toString () {
Return "myexception[" +detail+ "]";
}
}
Test class
public class Myselfexceptiontest {
static void Test (int index) throws myselfexception{
System.out.println ("The method parameter of the call is: Test (" +index+ ")");
if (index>10) {
throw new Myselfexception (index);
}
System.out.println ("No exception occurred");
}
public static void Main (string[] args) {
try {
Test (1);//No exception
Test (20);//exception
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Exception occurred:" +e);
E.printstacktrace ();
}
}
}
Java Custom Exceptions