Throw and Throws Keyword in Java

In this chapter, we are going to learn Throw and Throws keyword in Java. Before that, you must-read exception handling in Java and Try-Catch-Finally block in java.

Throw in Java:

Throw keyword is used to declare an exception explicitly. That means you can throw checked or unchecked exception from a method or block of code.

throw new ArithmeticException("Operation Not Allowed");

You can use throw keyword inside a method body.

Throws in Java:

Throws keyword is used to declare an exception from a method signature. Also, you can use your own custom exception to throw.

public void methodA() throws ArithmeticException{		
}

To declare an exception from a method we use throws keyword in the method signature. It denotes which exception can be thrown from a method.

The method may throw multiple exceptions and exceptions can be comma-separated.

public void methodA() throws NullPointerException, ArithmeticException, Exception{
		//method body
}

Difference between Throw and Throws Keyword in Java:

ThrowThrows
1. Used inside the method body1. Used in the method signature
2. Can’t throw multiple exceptions2. Can throw multiple exceptions from a method.

How to throw an Exception in Java with Example:

In order to throw an exception in Java, there are several ways including adding throw and throws keyword.

Therefore, it’s totally up to you and your requirement. If you’re using multiple if-else conditions then likely you should use throw keyword when any certain condition meets.

For instance, if you’re setting any database connection then you must add throws keyword to your method signature, describing that this method may throw a ConnectionException or SocketException.

Let’s take an example:

Example of Throw Keyword:

public class Example {
	public static void main(String[] args) {
		int age = 10;
		if (age > 18) {
			System.out.println("Above 18 years");
		} else {
			throw new ArithmeticException("Under Age");
		}
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Under Age

Example of Throws Keyword:

public class Example {
	public static void main(String[] args) {

		Example obj = new Example();
		System.out.println(obj.divisionMethod(20, 0));
	}

	public int divisionMethod(int a, int b) throws ArithmeticException {
		
		int div = a / b;
		return div;
	}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

I hope you’ve understood the difference between throw and throws keyword in Java. Now, continue to the next chapter.

Happy Learning!