web请求:
try{
WebRequest^ request = WebRequest::Create( s );
// If required by the server, set the credentials.
request->Credentials = CredentialCache::DefaultCredentials;
// Set the 'Timeout' property in Milliseconds.
request->Timeout = 10000;
// This request will throw a WebException if it reaches the timeout limit
// before it is able to fetch the resource.
myWebResponse = request->GetResponse();
}
catch(Exception^ e){....}
用结构化的异常处理方法来处理异常
在.NET Web服务中,对异常处理支持的关键点是由try...catch..finally语句提供的。关键字try放在可能抛出异常的普通处理代码块之前。关键字catch放在异常处理代码块之前。关键字finally放在那些经常在异常处理后还需要执行的代码块之前。一旦异常从try代码块中抛出,程序流切换到后面的第一个catch代码块。一套设计良好的错误处理代码块可以成功的使程序变得更加健壮,使程序崩溃的机率变得更小,那是因为应用程序处理像这样的错误所采取的方法的缘故。处理异常的最好实践可以总结如下:
经常用try/finally块包围潜在的可能发生错误的代码,并且把catch语句集中在一个地方。用这种方法,try语句抛出异常,finally语句关闭或释放资源,而catch语句则集中处理异常。
通常,catch语句块从非常特殊到一般来排列异常。这个技巧使得异常被传递到一般catch块之前先处理特殊异常。
大多数情况下,使用已有的异常类型。新的异常类型应该仅在有计划的情形下引进。
使用异常的构建方法。一个类的实现中在不同地方抛出同一个异常,这是非常普遍的现象。为了避免出现过量的这类代码,使用助手方法创建异常和返回异常。
文件读写:
创建一个文件,并把数据保存:
void AddText( FileStream^ fs, String^ value )
{
array<Byte>^info = (gcnew UTF8Encoding( true ))->GetBytes( value );
fs->Write( info, 0, info->Length );
}
Stream^ newdataStream = myWebResponse->GetResponseStream();
StreamReader^ newreader = gcnew StreamReader( newdataStream );
String^ newresponseFromServer = newreader->ReadToEnd();
String^ path = "c://temp.xml";
FileStream^ fs = File::Create( path );
try
{
AddText( fs, newresponseFromServer );
}
finally
{
if ( fs ) delete (IDisposable^)fs;
}
在一个存在文件后面添加内容,如果不存在,在创建这个文件:
void WriteLog(String ^path,CString str)//写Log
{
String^ ss = gcnew String(str);
StreamWriter^ sw = File::AppendText( path );
try
{
sw->WriteLine( ss );
}
finally
{
if ( sw )
delete (IDisposable^)sw;
}
}
1440

被折叠的 条评论
为什么被折叠?



