Java throw and throws keywords

In Java exception handling, throw keyword is used to explicitly throw an exception from a method or constructor. And throws keyword is used declare the list of exceptions which may be thrown by that method or constructor.

1. Java throw keyword

1.1. Syntax

To throw an exception from a method or constructor, use throw keyword along with an instance of exception class.

public void method() 
{
   //throwing an exception
   throw new SomeException("message");
}

1.2. Handling of checked vs unchecked exceptions

If we throw an unchecked exception from a method, it is not mandatory to handle the exception or declare in throws clause. For example, NullPointerException is an unchecked exception.

public class JavaExample 
{
	public static void main(String[] args) 
	{
		method();
	}
	
	public static void method( ) {
		throw new NullPointerException();
	}
}

But if we throw a checked exception using throw statement, we MUST either handle the exception in catch block or method much explicitly declare it using throws declaration. For example, FileNotFoundException is a checked exception.

public class JavaExample 
{
	public static void main(String[] args) 
	{
		try 
		{
			method();
		} 
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		}
	}
	
	public static void method( ) throws FileNotFoundException 
	{
		throw new FileNotFoundException();
	}
}

In Java, every subclass of Error and RuntimeException is an unchecked exception. A checked exception is everything else under the Throwable class.

1.3. Exception propagation

An exception propagates from method to method, up the call stack, until it’s caught. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.

The search for exception handler begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called, as described above.

When an appropriate handler (catch block) is found, the runtime system passes the exception to the handler. If no exception handler is found then exception reaches to JVM’s default exception handler which prints the exception details to logs and terminate the application.

2. Java throws keyword

Java throws keyword is used to declare a list of exceptions that may occur during the method execution.

2.1. Syntax

To declare the list of exceptions, use throws keyword along with exception class names.

public static void method( ) throws FileNotFoundException, ConnectionException {
	//code
}

2.2. Can throw checked and unchecked exceptions

We can declare both types of exceptions using throws clause i.e. checked and unchecked exceptions. But the method calling the given method must handle only checked exceptions. Handling of unchecked exceptions is optional.

public class JavaExample 
{
	public static void main(String[] args) 
	{
		try 
		{
			//Can skip handling of NullPointerException (unchecked exception)
			method();	
		} 
		catch (FileNotFoundException e) 
		{
			e.printStackTrace();
		}
	}
	
	public static void method( ) throws NullPointerException, FileNotFoundException {
		//code
	}
}

3. Difference between throw and throws in Java

  1. throw keyword is used to throw a single exception explicitly from any method or constructor while throws keyword is used in method and constructor declaration, denoted which exception can possible be thrown by this method.
  2. throw is followed by an instance of exception class while throws is followed by exception class name.
  3. throw is used within the method and constructor where as throws is used with the method and constructor signature.
  4. We can throw only single exceptions using throw but we can declare multiple exceptions using throws one of which may or may not throw by method.
  5. A checked exception is propagated to the caller method, while unchecked exceptions are not propagated thus may not require explicit exception handling.
  6. Using throw keyword we can also break a switch statement or a loop without using break keyword which cannot be performed using throws.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Java throw and throws keywords”

  1. “A checked exception is propagated to the caller method, while unchecked exceptions are not propagated thus may not require explicit exception handling.”

    This is quite not correct.

    The unchecked exception in fact does propagate through the method call stack and is being handled whenever it finds an explicit handler or propagates to the JVM and is being handled by the default JVM exception handler.

    Checked exceptions do not propagate. And as a result, this has to be explicitly mentioned/declared to the caller method in the call stack using throws keyword. It is a declaration to the caller method to provide a handler or propagate it to the next caller in the stack using the throws keyword. Even if the exception needs to be propagated to the JVM to be handled by default handler, you have to explicitly define/declare the Exception being thrown.

    Both unchecked and checked exception does occur at runtime. If you compile code with the lines :
    FileInputStream inputStream = new FIS(new File(“{filename}”);

    The compiler only checks if you have handled the Exception/declared the exception. There is no way compiler knows if the file exists/not and there will be an IOException.

    I think I reason behind the names checked and unchecked exception comes from the way compiler checks if you have declared all your exceptions which do not propagate (IOException/SQLException) and don’t check the ones which automatically propagate(RuntimeException). It is designed in a way where the compiler can pre-check the fact that checked exceptions can propagate.

    Please let me know what you think.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.