Difference Between Throw and Throws in Exception Handling

When you are working with exception handling in Java, use of throw and throws may confuse you if you not familiar with the exception handling. Both are important keywords used frequently used in handling the exceptions. Throw is used for explicitly throwing an exception. Throw attribute in method signature, is a hint to the compiler that the method raises an exception that must be caught by the caller. This kind of exception, namely called checked exception is something that the caller MUST always catch or dispatch to its caller again. The thrown exception must be a sub type of Throwable object which is the superior class for all the exceptions in Java.

Where as throws is used for handling the exceptions thrown from a method. It is equivalent of try-catch block, except throws can not perform any action with the exception. It is a default handler for exceptions that must be caught.

Look at the below example:

package javabeat.net.core;

import java.sql.SQLException;

public class ExceptionSample {

	//Unchecked exceptions are not handled using throws
	public void methodUncheckedException(){
		System.out.println("Throwing Unchecked Exception");
		throw new ArrayStoreException();
	}

	//Checked exceptions has to be handled using throws
	public void methodCheckedException() throws SQLException{
		System.out.println("Throwing Checked Exception");
		throw new SQLException();
	}

	public static void main(String args[]) {
		ExceptionSample exceptionSample = new ExceptionSample();
		exceptionSample.methodUncheckedException();
		try{
			exceptionSample.methodCheckedException();
		}catch (SQLException sqlException){
			sqlException.printStackTrace();
		}

	}
}

If you analyse the above example,

  • methodUncheckedException explicitcly throws ArrayStoreException. It is a run time exception which need not be handled. So, we are not adding the throws in the method signature.
  • methodCheckedException throws SQLException which is a checked exception and needs to be handled. So, we have added that exception in the throws statement. Also note that throws statement can specify more than one exception by separating using comma like throws SQLException, IOException.
  • Main method declares try-catch block for calling methodCheckedException, since it is throwing the check exception, it must be handled in the caller’s method too. Either try-catch block or using the throws statement.
  • Throws statement has to be used only when the thrown exception can not be handled in the same method and should propagate to the caller method. Otherwise you have to use the try-catch instead of throws statement.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*