Skip to main content

Java Keywords (Part XXIV): native

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. This is the last chapter of the Java Keyword series. This is probably the keyword I have used the least. In my 20 year career as a software developer, I have used this keyword once, and that was to make some addition to legacy code. The keyword native is a method modifier . Basically, it is a keyword that can only be applied to methods. According to the Java Language Specification (JLS), A method that is native is implemented i...

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.

Next up, Part XII: Implementing Interfaces and Extending Classes

Comments

Popular posts from this blog

Implementing Interfaces with Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Customizing Java Records " first and then come back to this one. Now that you know how to customize Java records, implementing an interface using Java records should be very easy to understand. If you don't know about interfaces in Java, you can read more on my article about interfaces. The recipe for implementing an interface is simply an expansion of what you learned in my previous blog on how to customize a Java record. Following our Rectangle example, let's create an interface with the same two methods we used before. public interface Shape { double area(); double perimeter(); } Now, let's further customize the previous example by doing two things: Add implements Shape at the end of the record declaration (after the record constructor), and Add @Override to the existing methods to ensure these methods com...

Customizing Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Java Keywords Addendum: The Java Record " first and then come back to this one. What is a customization of a record? A customization of a record is simply the addition of code inside the body of the class. Before proceeding further, let's recap important aspects of a Java Record: Java records are immutable Because of item 1 above, you cannot add new fields unless defined in the record constructor Java records already override: Object#equals(Object) and Object#hashCode() , and then override Object#toString() You could redefine overridden methods as part of your customization if you would like. For example, if you want a fancier implementation of the Object#toString() method, you could do so. Let's look at our first customization example. Using the example from my previous blog, public record Student(...

Object-Oriented Programming Basics: What is in a Class?

EDITORIAL NOTE : This article was published briefly back in 2016 and quickly set back to draft because I wasn't happy with its contents. It is a shame that it was taking me three years to revisit this topic and work on a new and improved version. At least, I'm hoping it will be to the liking you the reader. Keep in mind that the opening paragraph will still read as if I just wrote it for my (former) students at Texas Wesleyan. I started working on lecture on the topic of Object-Oriented (OO) Programming by gathering some material, old and new, when I realized this might be good and simple post for my second attempt at blogging. To be completely honest, in the 8 hours I spent collecting information and preparing material for this week's lecture, I realized I still made some of the mistakes I am about to blog about. I am actually hoping I can write a series of postings regarding Object-Oriented Programming (OOP). But to do so, I must start from the very beginning. ...