Thursday, 10 April 2014

Difference between throw and throws in Java

Throws: Throws declares that your method is capable of throwing an exception but it does not handle the exception that must be specified by using “throws” class.

When programmer defines a method and he knows that some part of code can raise an exception, and he don’t want to handle that exception within that function, then the method is defined with throws keyword.

Let us understand this with following example:


Imagine you have been assigned a task of finding a specific book, and then reading and explaining its contents to a class of students. The required sequence may look like:

  • Get the specified book
  • Read aloud its contents
  • Explain the contents to a class of students.



But what happens if you can't find the specified book? You can't proceed with the rest of the action without it so you need to report back to the person who assigned the task to you. This unexpected event (missing book) prevents you from completing your task. By reporting it back, you want the originator of this request to take corrective or alternate steps.


Let's code the above task as method teachClass, as shown in figure 1 and use it to compare the throw and throws statement. This example code is for demonstration purpose only because it uses methods locateBook, readBook, and explainContents, which aren't defined.

void teachclass () throws BookNotFoundException
{
      boolean bookFound = locateBook();
      if(!bookFound)
      {
            throw new BookNotFoundException();
             
      }
}

Code in figure 1 is simple to follow. On execution of code throw new BookNotFoundException, execution of teachClass() halts. The JVM creates an instance of BookNotFoundException and sends it to off to the caller of teachClass() so that alternate arrangements can be made.


The throw statement is used to throw an instance of exception—BookNotFoundException. The throws statement is used in the signature of method teachClass to signal that it can throw exception BookNotFoundException.

Why does a method choose to throw an exception as opposed to handling it itself? It's a contract between the calling method and the called method. Referring back to the method teachClass, as shown in figure 1, the caller of teachClass would like to be informed if teachClass is unable to find the specified book. The method teachClass doesn't handle BookNotFoundException itself because its responsibilities don't include how to work around a missing book.

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top