Trail: Java Naming and Directory Interface(TM).
Lesson: Naming and Directory Operations
Naming Exceptions
Home Page > Java Naming and Directory Interface(TM). > Naming and Directory Operations
Naming Exceptions
Many methods in the JNDI packages throw a NamingException when they need to indicate that the operation requested cannot be performed. Commonly, you will see a try/catch wrapper around the methods that can throw a NamingException:
try {
    Context ctx = new InitialContext();
    Object obj = ctx.lookup("somename");
} catch (NamingException e) {
    // Handle the error
    System.err.println(e);
}

Exception Class Hierarchy

The JNDI has a rich exception hierarchy stemming from the NamingException class. The class names of the exceptions are self-explanatory and are listed here .

To handle a particular subclass of NamingException specially, you catch the subclass separately. For example, the following code specially treats the AuthenticationException and its subclasses.

try {
    Context ctx = new InitialContext();
    Object obj = ctx.lookup("somename");
} catch (AuthenticationException e) {
    // attempt to reacquire the authentication information
    ...
} catch (NamingException e) {
    // Handle the error
    System.err.println(e);
}

Enumerations

Operations such as Context.list() and DirContext.search() return a NamingEnumeration . In these cases, if an error occurs and no results are returned, then NamingException or one of its appropriate subclasses will be thrown at the time that the method is invoked. If an error occurs but there are some results to be returned, then a NamingEnumeration is returned so that you can get those results. When all of the results are exhausted, invoking NamingEnumeration.hasMore() will cause a NamingException (or one of its subclasses) to be thrown to indicate the error. At that point, the enumeration becomes invalid and no more methods should be invoked on it.

For example, if you perform a search() and specify a count limit (n) of how many answers to return, then the search() will return an enumeration consisting of at most n results. If the number of results exceeds n, then when NamingEnumeration.hasMore() is invoked for the n+1 time, a SizeLimitExceededException will be thrown. See the count limit discussion of this lesson for a sample code.

Examples in This Tutorial

In the inline sample code that is embedded within the text of this tutorial, the try/catch clauses are usually omitted for the sake of readability. Typically, because only code fragments are shown here, only the lines that are directly useful in illustrating a concept are included. You will see appropriate placements of the try/catch clauses for NamingException if you look in the source files that accompany this tutorial.

The Exceptions in the javax.naming package can be found here .

Previous page: Naming and Directory Operations
Next page: Lookup an Object