Java Keywords (Part XI): Throwing Exceptions

We are up to 32 keywords covered in previous articles! That's 67% keywords covered. We have only 16 keywords to cover and I will be covering 2 of those in this article.

This article will illustrate the use of the keywords throw and throws, in Java Exception Handling. It will not get into specific usages of Exception Handling. For that, please go to my article covering this topic. Also, be on the lookout for a new article covering other facets of Java Exception Handling, such as "try with resources."

I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
In Part X of this series, you learned how to properly construct a "try/catch/finally" block. If you recall, I never mentioned any details on how an application is made aware that the execution of a particular line of code resulted in an exception or error. But, as you might have guessed by now, the mechanism to make an application aware is by the use of the keywords already mentioned in this article: throw and throws.

The throw Keyword

Using the same code example from the previous article, we can add the use of throw keyword to make the code more complete:

public void writeEntry (String filePath, String entry) {

  try {

    FileWriter fileWriter = new FileWriter(filePath, true);
    fileWriter.append("/n");
    fileWriter.append(entry);
    fileWriter.close();

  } catch (IOException ioe) {
    // Log the error
    throw ioe;
  }

  // Do more stuff...
}
Adding "throw" inside the catch serves two purposes. The first purpose is to immediately stop the execution of subsequent code (Except for code in the "finally" block), and to send a "signal" to the caller of the method that something went wrong. This is important to know as you will see later in the "Order of Execution" section. However, using this keyword alone is not enough. If you are coding along to this example, you will notice that adding this keyword will result in a compiling error. The reason is that you must also use the keyword throws to indicate to the caller that the enclosing method can throw some kind of exception during execution. To conclude the usage of the keyword throw, you should know that this using this keyword is not restricted to inside the "catch" block; or even inside the "try." This keyword can be used anywhere inside the method body. The following example illustrates a possible case:

public Sting doSomethingAndReturnString () {

  String myString = null;
  //Do something to set a value on myString....

  if (myString == null) {
    throw new IllegalArgumentException("myString cannot be null");
  }

  return myString;
}
In this example, we have no "try/catch." Here, I simply create a new instance of the illustrated exception and throw it in case the value of my string is null.

The throws Keyword


public void writeEntry (String filePath, String entry) throws IOException {

  try {

    FileWriter fileWriter = new FileWriter(filePath, true);
    fileWriter.append("/n");
    fileWriter.append(entry);
    fileWriter.close();

  } catch (IOException ioe) {
    // Log the error
    throw ioe;
  }

  // Do more stuff...
}
If you notice in the method signature, I added a "throws" clause. This is what alerts callers of this method that something can go wrong during execution and that resulting exceptions must be handled by the caller. Also noticed that the type of exception declared must match the exceptions actually being thrown. In the case your code can throw multiple exceptions, the "throws" clause must have them listed separated by comma. Again, for more details, refer to my articles on Exception Handling. For now, you have learned how to use this keyword properly.

Order of Execution

It is important that we cover the order of execution of instructions inside a "try/catch/finally" block. Let's use the following example to illustrate:

public void writeEntry (String filePath, String entry) {

  System.out.println("Before the try/catch/finally");
  try {

    System.out.println("Inside the try(1)");
    System.out.println("Inside the try(2)"); // Assume exception occurs here

  } catch (IOException ioe) {
    System.out.println("Inside the catch");
    throw ioe;
  } finally {
    System.out.println("Inside the finally");
  }
  System.out.println("After the try/catch/finally");
}
Assuming an exception occurs where indicated, the output of the program will be as shown below:

Before the try/catch/finally
Inside the try(1)
Inside the catch
Inside the finally
If you recall, in Part X, the line "After the try/catch/finally" was printed out after execution of the "finally" block. However, in this example, due to the addition of the throw, that line will never be executed. However, if the exception never occurs, it will simply execute the previously skipped line and the code inside the "catch" will not be executed.

Before the try/catch/finally
Inside the try(1)
Inside the try(2)
Inside the finally
After the try/catch/finally

Closing Words

In parts X and XI of these series, you have learned the correct usage of the 5 keywords necessary to implement all aspects of Exception Handling in the Java language. You should learn these keywords and their application in Exception Handling as this is one of those questions that always seem to be asked in Java programming job interviews. In fact, keywords and their usage is normally asked in entry-level interviews.

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

The Beauty of the Null Object Pattern

Exception Handling: File CRUD Operations Example