We have seen examples of Throw and Throws in some of our previous posts.
Throw and Throws keyword are used in different scenarios while doing exception handling. In this post we see some basic difference between Throw and Throws.
Difference between Throw and Throws
1. Syntax
Throws
1 |
public Employee searchEmployee(String firstName) throws EmployeeNotFoundException |
Throw
1 2 3 4 |
Employee employee = employeeSearchService.findEmp(firstName); if (employee == null) { throw new EmployeeNotFoundException("Employee with FirstName " + firstName + " not found"); } |
2. Use
When you want to explicitly throw an exception for a specific purpose then you use throw keyword.
When you want to tell the end user that a method can throw an exception then you use throws keyword to declare exception in the method signature
3. Instance Vs Class
We use throw keyword with an instance of object, whereas throws is used with Class
4. Inside Vs Outside
Throw is used inside a the method’s body. Throws is used with the method signature.
5. Single Vs Multiple
Since throw is used inside a method, you can only throw one exception at a time.
Since throws is used in method signature you can use multiple exceptions with the throws keyword.
1 |
public Employee searchEmployee(String firstName) throws EmployeeNotFoundException, InvalidEmployeeNameException |
These are some of the difference between throw and throws keyword used in the exception handling in java.