下面的代码中如果连接服务器出现异常就会抛出异常throw new FTPException("Can not Connect the Server");
但是程序也就在此中断了,请问怎么才能避免这种情况?throw是不是只有在测试中有用呢?
public virtual void Connect()
{
lock (clientLock)
{
                bool loggedIn = false;
try
{
                    if (LocalDirectory==null)
                        LocalDirectory = Directory.GetCurrentDirectory();
                    if (ServerAddress == null)
                        throw new FTPException("ServerAddress not set");
                    OnConnecting();
                    ActiveClient.Connect();
                    log.Debug("Connected to " + ServerAddress + " (instance=" + instanceNumber + ")");
                    OnConnected(true);
                    loggedIn = PerformAutoLogin();
                }
catch
{//此处进行了修改
OnConnected(IsConnected);
if (!IsConnected)
OnClosed();
throw new FTPException("Can not Connect the Server"); }
                if (loggedIn) 
                    PostLogin();
            }

解决方案 »

  1.   

    根据你的需求,你应该在Application_Error事件中处理这些异常。
    建议你看一下http://www.cnblogs.com/hejunrex/archive/2010/01/20/1652084.html
      

  2.   

    我的这段代码是用在Winform模式中的
    不知道把throw new FTPException("Can not Connect the Server"); 去掉会有什么影响
      

  3.   

    为什么去掉?既然执行这句话了,那就说明发生错误了,然后再catch中捕获它并处理呗,去掉它干嘛呢
      

  4.   

    throw 语句是抛出异常用的,程序经常需要这种情况,就是 当出现某种可能的错误时 人为的抛出一个异常象这样: throw new Exception("输出的值范围在 >0到<100 之间");比如这样的抛出异常在某个方法中 这个方法叫XXX 那么你在调用这样的方法中 记得捕捉异常就行了象这样 : void YYY(){ try{ this.XXX();} catch(Exception e){ MessageBox.Show(e.Message);}}就可以了
      

  5.   

    我的意思是在
    catch 
    {//此处进行了修改 
    OnConnected(IsConnected); 
    if (!IsConnected) 
    OnClosed(); 
    throw new FTPException("Can not Connect the Server"); 

    中已经捕获到了异常,那么我就不需要再throw new FTPException("Can not Connect the Server");
    如果在catch中捕获怎么写呢?
      

  6.   

    catch(Excetpion e)
    {
      throw new Exception(e.Message);
    }
      

  7.   

    throw异常时,程序就退出正常的执行序列,跳转到第一个catch这个异常的地方去了。
      

  8.   

    你已经用Catch 住异常了 而你又不能处理异常。你有两种选择1:抛出异常让外面的Try去捕获对其进行操作。2:你的这个方法public virtual void Connect() 就可以修改为public virtual bool Connect()  返回一个值给客户端,例如返回True 则成功,Flase 不成功。提示是什么原因就OK。
      

  9.   

    个人觉得在实践中,何时抛出异常,何时捕捉异常,无一定之规。常见的有,捕捉所有异常,后以Bool结果返回。代码中又常见不捕捉异常,直接调用,直到异常发生,系统退出。
    处理关键在于函数调用的约定:谁抛出异常,谁处理异常。