Microsoft SDK for Java

Handling COM Errors in Java

This section discusses HRESULTs in connection with ComFailException objects and try-catch blocks. An error handling example is included.

HRESULTs

HRESULTs are 32-bit error codes returned by every COM interface method to indicate success or failure of a method call. Usually, only the success code (S_OK) is defined, but many other failure codes can be defined. For a list of the values of common system-defined HRESULTs, see the ComFailException class. For domain-specific errors, see the documentation for the component you are using.

The documentation for many components describe errors in terms of Visual Basic Err.Number values rather than HRESULTs. However, some components use a convention in which the returned HRESULT corresponds with the Err.Number value. For example, if you are using Data Access Objects (DAO) or Remote Data Objects (RDO), you can call the getHResult method on the ComFailException object, take the lower 16 bits of the returned HRESULT, convert that value to decimal, and check it against the errors described in the DAO or RDO documentation.

The ComException class wraps the HRESULT error code and is used to communicate error information from COM back to Java whenever a COM method fails. The ComException class defines a getHResult method that returns the error code as a Java integer. You can also use java.lang.Throwable.getMessage( ) to retrieve the error message associated with the exception or error.

Try-Catch Blocks

The Microsoft VM throws an exception when a call to a COM interface method returns an HRESULT containing an error code. Try-catch blocks handle these errors or exceptions. Because the ComException class is derived from java.lang.RuntimeException, the compiler does not strictly require a throws clause in the method declaration, nor does it require try-catch blocks. Because runtime exceptions are unchecked by the compiler, you can use try-catch blocks when you need them.

Because ComException is an abstract class, a ComException object cannot be constructed directly. However, a ComFailException object or a ComSuccessException object can be constructed. Typically, catch ComFailException objects so it's obvious that something has gone wrong during a call to a COM method. The following example demonstrates the use of a try-catch block.

try
{
   // Call COM method.
}
catch (com.ms.com.ComFailException e)
{
   System.out.println( "COM Exception:" );
   System.out.println( e.getHResult() );
   System.out.println( e.getMessage() );
}

An Error Handling Example

The following Java code is similar to the code in Implementing COM Interfaces; however, error handling has been added.

import robocorp.bots.*;
...
try
{
         Robot robbie = new Robot();
         robbie.GoForward(10);
         robbie.Turn(-90);
}
catch(Throwable e)
{
         System.out.println("Something bad happened!");
}

© 1999 Microsoft Corporation. All rights reserved. Terms of use.