Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Introduction to Java programming, Part 2: Constructs for real-world applications

More-advanced Java language features

J Steven Perry, Principal Consultant, Makoto Consulting Group, Inc.
Photo of J Steven Perry
J. Steven Perry is a software developer, architect, and general Java nut who has been developing software professionally since 1991. His professional interests range from the inner workings of the JVM to UML modeling and everything in between. Steve has a passion for writing and mentoring; he is the author of Java Management Extensions (O'Reilly), Log4j (O'Reilly), and the IBM developerWorks articles "Joda-Time" and OpenID for Java Web applications." In his spare time, he hangs out with his three kids, rides his bike, and teaches yoga.

Summary:  In Part 1 of this tutorial, professional Java™ programmer J. Steven Perry introduced the Java language syntax and libraries you need to write simple Java applications. Part 2, still geared toward developers new to Java application development, introduces the more-sophisticated programming constructs required for building complex, real-world Java applications. Topics covered include exception handling, inheritance and abstraction, regular expressions, generics, Java I/O, and Java serialization.

View more content in this series

Date:  19 Aug 2010
Level:  Introductory PDF:  A4 and Letter (904 KB | 53 pages)Get Adobe® Reader®

Comments:  

Exceptions

No program ever works 100 percent of the time, and the designers of the Java language knew this. In this section, learn about the Java platform's built-in mechanisms for handling situations where your code doesn't work exactly as planned.

Exception-handling basics

An exception is an event that occurs during program execution that disrupts the normal flow of the program's instructions. Exception handling is an essential technique of Java programming. In essence, you wrap your code in a try block (which means "try this and let me know if it causes an exception"), and use it to catch various types of exceptions.

To get started with exception handling, take a look at the code in Listing 10:


Listing 10. Do you see the error?

// . . .
public class Employee extends Person {
// . . .
 private static Logger logger;// = Logger.getLogger(Employee.class.getName());

 public static void main(String[] args) {
   Employee employee1 = new Employee();
   employee1.setName("J Smith");
   Employee employee2 = new Employee();
   employee2.setName("J Smith");
   logger.info("Q: employee1 == employee2?      A: " + (employee1 == employee2));
   logger.info("Q: employee1.equals(employee2)? A: " + employee1.equals(employee2));

 }

Notice that the initializer for the static variable holding the Logger reference has been commented out. Run this code and you'll get the following output:

Exception in thread "main" java.lang.NullPointerException
 at com.makotogroup.intro.Employee.main(Employee.java:54)

This output is telling you that you are trying to reference an object that isn't there, which is a pretty serious development error. Fortunately, you can use try and catch blocks to catch it (along with a little help from finally).

try, catch, and finally

Listing 11 shows the buggy code from Listing 10 cleaned up with the standard code blocks for exception handling try, catch, and finally:


Listing 11. Catching an exception

// . . .
public class Employee extends Person {
// . . .
 private static Logger logger;// = Logger.getLogger(Employee.class.getName());

 public static void main(String[] args) {
   try {
     Employee employee1 = new Employee();
     employee1.setName("J Smith");
     Employee employee2 = new Employee();
     employee2.setName("J Smith");
     logger.info("Q: employee1 == employee2?      A: " + (employee1 == employee2));
     logger.info("Q: employee1.equals(employee2)? A: " + employee1.equals(employee2));
   } catch (NullPointerException npe) {
     // Handle...
     System.out.println("Yuck! Outputting a message with System.out.println() " +
                        "because the developer did something dumb!");
   } finally {
     // Always executes
   }
 }

Together, the try, catch, and finally blocks form a net for catching exceptions. First, the try statement wraps code that might throw an exception. If it does, execution drops immediately to the catch block, or exception handler. When all the trying and catching is done, execution continues to the finally block, whether or not an exception has been thrown. When you catch an exception, you can try to recover gracefully from it, or you can exit the program (or method).

In Listing 11, the program recovers from the error, then prints out a message to report what happened.


The exception hierarchy

The Java language incorporates an entire exception hierarchy consisting of many types of exceptions grouped into two major categories:

  • Checked exceptions are checked by the compiler (meaning the compiler will make sure that they get handled somewhere in your code).
  • Unchecked exceptions (also called runtime exceptions) are not checked by the compiler.

When a program causes an exception, you say it throws the exception. A checked exception is declared to the compiler by any method with the keyword throws in its method signature. This is followed by a comma-separated list of exceptions the method could potentially throw during the course of its execution. If your code calls a method that specifies that it throws one or more types of exceptions, you must handle it somehow, or add a throws to your method signature to pass that exception type along.

In the event of an exception, the Java language runtime searches for an exception handler somewhere up the stack. If it doesn't find one by the time if reaches the top of the stack, it will halt the program abruptly, as you saw in Listing 10.

Multiple catch blocks

You can have multiple catch blocks, but they must be structured in a particular way. If any exceptions are subclasses of other exceptions, then the child classes are placed ahead of the parent classes in the order of the catch blocks. Here's an example:

try {
 // Code here...
} catch (NullPointerException e) {
 // Handle NPE...
} catch (Exception e) {
 // Handle more general exception here...
}

In this example, the NullPointerException is a child class (eventually) of Exception, so it must be placed ahead of the more general Exception catch block.

You've seen just a tiny glimpse of Java exception handling in this tutorial. The topic could make a tutorial on its own. See Resources to learn more about exception handling in Java programs.

3 of 14 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=508383
TutorialTitle=Introduction to Java programming, Part 2: Constructs for real-world applications
publish-date=08192010
author1-email=steve@makotoconsulting.com
author1-email-cc=jaloi@us.ibm.com