Java Keywords (Part X): Try, Catch, and Finally Blocks

We are up to 29 keywords covered in previous articles! That's 60% keywords covered. We have only 19 keywords to cover and I will be covering 3 of those in this article.

This article will illustrate the use of the keywords try, catch, and finally, 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.
After another long hiatus, I am back to finish what I started in 2018.

The classic "Try/Catch"

I cannot say this for certain, but I believe most examples of Java exception handling will fall under this category; which I am calling the classic form.

try {
    // primary execution path
} catch (Exception e) {
    // secondary execution path
}
Have you ever heard the phrase "time for Plan B"? Well, that is precisely what exception handling does. The purpose of Exception Handling is to provide a mechanism through which it will be possible to execute an alternate execution path if some erroneous (exceptional) condition arises. Although I will not cover how the application is alerted of such conditions in this article, I will cover that in the next article of this series. In this context, you can say that Plan A is the primary execution path and Plan B is the alternate. What would be the alternative to Exception Handling? The alternative will be to let the application crash which we can all agree is really a terrible alternative. Java provides the mechanism to handle these conditions with the keywords illustrated in this article. But without getting off further on this little tangent, let's go back to the use of the classic "try/catch".

Suppose you write an application to make entries in a journal or a diary. You may have in your application a method to post an entry into a given file:


public void writeEntry (String filePath, String entry) {

    FileWriter fileWriter = new FileWriter(filePath, true);
    fileWriter.append("/n");
    fileWriter.append(entry);
    fileWriter.close();
}
On the surface, this looks fine. After all, this example is making use of a proven class from a Java library to provide an object whose job is to write to files. Once obtaining the file, we simply write to it and close the file when we are done. But, what if the file doesn't exist? Could you simply write to a file that does not exist? The answer to this question is "no." However, Java does create the file for you if it doesn't exist and writes to a file with the given name in the given path IF you have the necessary permissions from the Operating System to create a file in that location. Because something can go wrong during the file accessing or file creation process, we must handle that possibility to allow the application to either fail gracefully (i.e. displaying an error message to the user before closing) or continue. Both of these outcomes could be considered a form or "Plan B". Because something can go wrong with any of these lines of code, we must surround them within a "try/catch" block.

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) {
    // Do something here
  }
}
Now, if something goes wrong during the execution of these lines, I can program what I want the application to do in the event that this occurs. I am going to end this example here. Remember that the goal of this article is to illustrate the use of the keywords and not necessarily get deep in the details of Exception Handling.

The Finally Block

This is a simple one to illustrate, but sometimes a bit difficult to comprehend. I remember when I first got into programming, it was a bit confusing (in some cases) grasp how the "finally" block worked. In the simplest of terms, the "finally" block is reserved for code that we want to execute always regardless of the result of the execution of the "try" block. In other words, the code inside the "finally" block will always execute, regardless of whether or not an exception occurs.

Expanding on the existing example, what happens if the file writer object is created, but something goes wrong during the writing operation? If this occurs, the file writer object will never be closed. Is this a bad thing? For now, accept "Yes" as the answer. Fortunately, we can write our program to always close this resource by putting that line inside our "finally" block.


public void writeEntry (String filePath, String entry) {

  FileWriter fileWriter = null;
  try {

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

  } catch (IOException ioe) {
    // Do something here
  } finally {
    fileWriter.close();
  }
}
Notice that I moved the declaration of the file writer object outside the "try" block. This is because of something known as "scope." In order for variables to be accessible in multiple blocks, they must be declared in a block common to these blocks. In Java, a block is defined as the space (lines) declared between curly braces {...}. In this example, "try" is a block and "finally is another block. Anything declared inside any of these blocks is only visible there. For file writer object to be accessible to the "try" and "finally" blocks, I needed to graduate the declaration of this variable to the method block.

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");
  } 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
After the try/catch/finally
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
In the next article, we will revisit the order of execution once again.

Closing Words

I have illustrated the use of the try, catch, and finally keywords. As I previously stated, please refer to my other articles on Exception Handling for more information, or contact me with your specific questions. I will get back to you with an answer and/or use your questions to improve an existing article or write a new one altogether.

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

The Beauty of the Null Object Pattern

Java Keywords (Part I): Creating Classes