Java throws


The throws keyword is mainly used to declare an exception.

 

When a method is not able to handle a checked exception, then the method should use the throws keyword.

 

The throws keyword appears with the method's signature.

Syntax:

 Datatype MethodName() throws ExceptionName{  
// Method implementation
}   

Example

public class ThrowsException
{ 
    static void age() throws IllegalAccessException 
    { 
        int a=12;
        if(a>18)
        {
            System.out.println("Right to vote"); 
        }
        else{
            throw new IllegalAccessException("Not eligible");
        }
        
    } 
    public static void main(String args[]) 
    { 
        try
        { 
            age(); 
        } 
        catch(IllegalAccessException e) 
        { 
            System.out.println("Exception handled"); 
        } 
    } 
} 

Difference between throw and throws.

S.No throw throws
1 The 'throw' keyword is used to invoke an exception explicitly. The 'throws' keyword is mainly used to declare an exception.
2 The throw should be used within the method. The throws keyword appears with the method's signature.
3 Throw is followed by an instance of exception class. Throws is followed by exception class name.
4 You can throw only one exception at a time. You can declare multiple exceptions at a time. e.g. public MethodName() throws Exception 1, Exception 2.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.