How Do I...Handle WebException?
This sample illustrates how to use the WebException and
UriFormatException classes when dealing with exceptions
when accessing URIs.
This sample is like the simple clientGET sample.
The most important sections of code here (other than adding a try and
catch to make sure we catch exceptions) are the catch sections.
In this catch section, the object that is caught is of type
WebException or UriFormatException. Both exception
objects have an exception message that can be
written out with the ToString() method. In addition,
you can examine the
error code of the WebException with the call to its
Status property. If this status is
WebExceptionStatus.ProtocolError,
then you can get the WebResponse and see its status code,
which will map to an HTTP status code.
Run ClientWebException.exe and try these URLS:
htto://www.microsoft.com
(Bad URI, invalid protocol)
http://serverthatdoesntexist
(Name could not be resolved)
http://authserver/somauthtype
(server that requires authentication)
file://c:\
(Access is denied)
Example
C# ClientWebException.exe
[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\net\WebRequests\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild
passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin
directory.]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|