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. |
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.