Difference between throw and throws in java

Previous
Next

In this tutorial, we are going to see difference between throw and throws in java.

throw:

throw keyword is used to throw any custom exception or predefine exception.
For example:
Let’s say you want to throw invalidAgeException when employee age is less than 18.
Create a Employee class as below.

Create InvalidAgeException class as below

Now create a main class named EmployeeExceptionTest.java as below.

when you run above program, you will get below output:

throws:

throws keyword is used to declare list of all exception which method might throw. It delegates responsibility of handling exception to calling method.
For example:
Let’s say you want to declare InvalidAgeException in setAge() method when employee age is less than 18 and InvalidAgeException exception should be handled in main method.
Create a Employee class as below.

Create InvalidAgeException class as below

Now create a main class named EmployeeExceptionTest.java as below.

when you run above program, you will get below output:

If you notice, we have used throws keyword in Employee’s setAge method instead of handling InvalidAgeException.

Now we have used try catch block in main method to handle InvalidAgeException.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog