So far you have been using the pre-defined exception classes provided by the Java API. However, if you encounter a problem that cannot be adequately described by the predefined exception classes, you can create your own exception class.
In order to create your own exception class, you just need to define a class that extends one of the classes in the Java exception hierarchy. Most of time you create your own exception class by extending the Exception class or one of its subclasses such as IOException.
Like any other class, the exception class that you create can contain fields and methods. However, a new exception class typically contains only two constructors, one that takes no argument and passes a default exception message to the super class constructor and other that receives a customized exception message as a string and passes it to the superclass constructor. This specified message will be set in the Exception object and can be obtained by invoking getMessage () method on the object.
Suppose you are developing a new exception class named InvalidRadiusException which will be thrown if the radius is negative while calculating area of circle.
class InvalidRadiusException extends Exception { InvalidRadiusException() { super(); } InvalidRadiusException(String message) { super(message); } }
Since our exception class InvalidRadiusException extends Exception which further extends Throwable class so all the methods of the Throwable class such as getMessage () toString () , printStackTrace () etc. are automatically inherited is the exception class.
Once your have created your own exception class, you can create an object of this Exception class with an appropriate message and throw the exception where it is needed using the throw statement.
class InvalidRadiusException extends Exception { InvalidRadiusException() { super(); } InvalidRadiusException(String message) { super(message); } } class Circle { private int radius; Circle(int r) throws InvalidRadiusException { setRadius(r); } public void setRadius(int r) throws InvalidRadiusException { if(r>=0) radius = r; else throw new InvalidRadiusException("Radius Cannot be Negative"); } public void area() { System.out.println("Area of circle is = "+(Math.PI*radius*radius)); } } class CustomException { public static void main(String[] args) { try { circle c1 = new Circle(3); c1.area(); circle c2 = new Circle(-5); c2.area(); circle c3 = new Circle(2); c3.area(); } catch(InvalidRadiusException e) { System.out.println(e.getMessage()); } } }