代码改变世界

c#.net内部异常捕获问题

2011-01-07 18:32  smat  阅读(2349)  评论(2编辑  收藏  举报

public static void Download()
        {
            
int count = 0;
            
try
            {
                HttpWebRequest request 
= (HttpWebRequest)WebRequest.Create("http://img.bimg.126.net/photo/c7bckFJxdJxSwQLIy76HTQ==/1755840904721658663.jpg");
                
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    
byte[] buffer = new byte[64];
                    
string temppath = "g:\\1755840904721658663.jpg";

                    
using (System.IO.Stream downloadStream = response.GetResponseStream())
                    {
                        
using (FileStream saveFileStream = new FileStream(temppath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            
int readSize = 0;
                            
while (true)
                            {
                                readSize 
= downloadStream.Read(buffer, 0, buffer.Length);
                                
if (readSize <= 0break;
                                saveFileStream.Write(buffer, 
0, readSize);
                            }
                            Console.WriteLine(
"弹出");
                        }
                    }
                }
            }
            
catch (System.Net.Sockets.SocketException ex)
            {
                Console.WriteLine(
"网络中断");
            }
            
catch (Exception ex)
            {
                
//throw ex;
                Console.WriteLine("异常类型:{0}", ex.GetType());
                Console.WriteLine(
"异常信息:{0}", ex.Message);
                Console.WriteLine(
"异常来源:{0}", ex.Source);
                Console.WriteLine(
"异常堆栈:{0}", ex.StackTrace);
                Console.WriteLine(
"内部异常:{0}", ex.InnerException);
            }
        }

异常类型:System.IO.IOException
异常信息:无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。
内部异常:System.Net.Sockets.SocketException (0x80004005): 远程主机强迫关闭了一
个现有的连接。
  在 System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size,
 SocketFlags socketFlags)
  在 System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)

IOException.InnerException是因为在读取Stream过程中,网络中断导致。

所以代码中应该加上一个Catch IOException的处理。

...
catch(IOException ex)
{
   
if(IOException.InnerException is System.Net.Sockets.SocketException)
       Console.WriteLine(
"网络中断");
   
else
       Console.WriteLine(ex.Message);
}
...