Java Custom Exceptions: (Exceptions here)
In Java, developer can customize the exceptions. The developer has to write a class that extends Exception and can customize the exception.

Before we proceed further, Let us try to understand two keywords throw and throws

throw throws
throw is used to throw and exception from any method throws is used in method declaration
throw is used within a method throws is used with method signature
throw can be used only once within a method throws can declare more than once exception

Now let us see an example for Custom Exception,

package ExceptionHandling;
public class ExceptionHandling {
    
    class customException extends Exception{
        public customException(String s){
            super(s);
        }
    }
    
    public void validate(int i)throws customException{
        if(i>20){
            throw new customException("Not Qualified");
        }
        else
        {
            System.out.println("Qualified");
        }
        
    }
    
    public static void main(String args[]) throws customException{
       ExceptionHandling exceptionHandling = new ExceptionHandling();
       exceptionHandling.validate(22);
    }   
}

In the above example, We have declared throws customException. We can declare multiple exceptions there. Example: Throws IO Exception, Arithmetic Exceptions etc. But we will be able to declare throw only once within a method.

Output:
op

Exceptions – Here

By Sri

One thought on “Java Custom Exceptions”

Leave a Reply

Your email address will not be published. Required fields are marked *