Java Keywords (Part X): Try, Catch, and Finally Blocks
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 |
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
}
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();
}
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
}
}
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();
}
}
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");
}
Before the try/catch/finally
Inside the try(1)
Inside the catch
Inside the finally
After the try/catch/finally
Before the try/catch/finally
Inside the try(1)
Inside the try(2)
Inside the finally
After the try/catch/finally
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.Next up, Part XI: Throwing Exceptions
Comments
Post a Comment