throw and throws are the two keywords used to declare an exception in Java. They are very useful for programmers who have to handle exceptions.
| Throw | Throws | 
|---|---|
throw is followed by an instance. For example: throw new SQLException(“SQL Exception”); | 
throws is followed by a class name i.e., throws SQLException; | 
throw is used within a method. | 
throws is used next to the method signature. | 
A programmer cannot throw multiple throws at a single time. | 
A programmer can throw multiple throws at a single time. For example: throws IOException, ArithmeticException; | 
The throw keyword explicitly throws an exception. | 
The throws keyword declares an exception and works similarly to the try-catch block. | 
throw codeThe following example shows how to use the throw keyword in Java; it displays the exception once it occurs.
class Code{void checkMarks(int marks){if(marks<50)throw new ArithmeticException("Exam failed");elseSystem.out.println("Exam passed");}public static void main(String args[]){Code object = new Code();object.checkMarks(43);}}
throws codeThe following example explains how to use the throws keyword in java.
class Code{int checkMarks(int marks) throws ArithmeticException{int result= marks/0;return result;}public static void main(String args[]){Code object = new Code();try{System.out.println (object.checkMarks(43));}catch(ArithmeticException except){System.out.println("Error in dividing number by zero");}}}
Free Resources