18.04.2015 Views

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

ArcGIS Engine Developer Guide

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

.NET APPLICATION PROGRAMMING INTERFACE<br />

clean up resources such as file handles or database connections.<br />

If you do not have any cleanup code, you do not need to include a Finally block.<br />

Code without exception handling<br />

If a line of code not contained in a Try block throws an error, the .NET runtime<br />

searches for a Catch block in the calling function, continuing up the call stack<br />

until a Catch block is found.<br />

If no Catch block is specified in the call stack, the exact outcome may depend on<br />

the location of the executed code and the configuration of the .NET runtime.<br />

Therefore, it is advisable to include at least a Try, Catch, Finally construct for all<br />

entry points to a program.<br />

Errors from COM components<br />

The structured exception handling model differs from the HRESULT model used<br />

by COM. C++ developers can easily ignore an error condition in an HRESULT if<br />

they want; in Visual Basic 6, however, an error condition in an HRESULT populates<br />

the Err object and raises an error.<br />

The .NET runtime’s handling of errors from COM components is somewhat<br />

similar to the way COM errors were handled at VB6. If a .NET program calls a<br />

function in a COM component (through the COM interop services) and returns<br />

an error condition as the HRESULT, the HRESULT is used to populate an<br />

instance of the COMException class. This is then thrown by the .NET runtime,<br />

where you can handle it in the usual way, by using a Try, Catch, Finally block.<br />

Therefore, it is advisable to enclose all code that may raise an error in a COM<br />

component within a Try block with a corresponding Catch block to catch a<br />

COMException. Below is the first example rewritten to check for an error from a<br />

COM component.<br />

[VB.NET]<br />

Dim env As IEnvelope = New EnvelopeClass()<br />

env.PutCoords(0D, 0D, 10D, 10D)<br />

Dim trans As ITransform2D = env<br />

trans.Rotate(env.LowerLeft, 1D)<br />

Catch COMex As COMException<br />

If (COMex.ErrorCode = -2147220984) Then<br />

MessageBox.Show("You cannot rotate an Envelope")<br />

MessageBox.Show _<br />

("Error " + COMex.ErrorCode.ToString() + ": " + COMex.Message)<br />

End If<br />

Catch ex As System.Exception<br />

MessageBox.Show("Error: " + ex.Message)<br />

...<br />

[C#]<br />

{<br />

IEnvelope env = new EnvelopeClass();<br />

env.PutCoords(0D, 0D, 10D, 10D);<br />

ITransform2D trans = (ITransform2D) env;<br />

Chapter 4 • <strong>Developer</strong> environments • 155

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!