当前位置:编程学习 > C#/ASP.NET >>

求:怎么捕获当前线程中未处理的异常

public class test : IDisposable
    {
        public void Dispose()
             {
            //我异常了吗?
        }
    }

执行下面的代码,怎么在test的Dispose方法中判断是否异常了?
using (test t = new test())
{
    throw new ArgumentNullException();
}
--------------------编程问答-------------------- 不用using
换用
try
{
}
catch
{
}
finally
{
} --------------------编程问答-------------------- 想用 currentDomain.UnhandledException 事件,但总是不触发这个事件。
或者说在执行Dispose方法前不会执行呢? --------------------编程问答-------------------- 在Class的声明里面加一个Exception属性.
如果出现异常不抛出,而是给Exception赋值...
而要在需要的时候去判断是否为空?为空证明没有错误.
如果是Form的程序,就简单多了.去找找资料吧...好像有2个事件可以捕捉到的...其中有一个就是未处理的错误... --------------------编程问答-------------------- 这段代码只是举一个例子。
我是要了解,在Dispose方法中到底怎么获取未处理的异常。 --------------------编程问答-------------------- 因为using实际被编译的时候是
try
{
}
finally
{
}

你异常被拦截没了,所以你无法再外面捕获到的。你如果想扔出异常。

test t = null;
try
{
    t = new test();
    //t....
}
catch
{
    throw;
}
finally
{
    if(t!=null)t.Dispose();
}
--------------------编程问答-------------------- public class test : IDisposable
  {
    public Exception excep;
  public void Dispose()
  {
     if(excep != null)
     {  //我异常了; }
  //我异常了吗?
  }
  }

执行下面的代码,怎么在test的Dispose方法中判断是否异常了?
using (test t = new test())
{
    try
    { throw new Exception("一个错误"); }
    catch(Exception e)
    { t.excep = e;}
} --------------------编程问答--------------------
引用 5 楼 wuyazhe 的回复:
...
你异常被拦截没了,所以你无法再外面捕获到的。你如果想扔出异常。
test t = null;
try
{
    t = new test();
    //t....
}
catch
{
    throw;
}
finally
{
    if(t!=null)t.Dispose();
}

多此一举:)

另,Dispose不应该过问使用过程中是否发生异常(可能是别人的异常),
而应该关心自己,是否应该,应该做什么样的清理。比如:


if( this.Connection != null )
{
   this.Connection.Close();
}
--------------------编程问答-------------------- 这个么。。
比如这样呢?不算多余吧,如果不处理,外面吧异常处理了,但这个串口对象就要等垃圾回收来回收了,否则就占用无法释放了,对不 :)

SerialPort comm = null;
try
{
    comm = new SerialPort();
    //模拟其他操作导致异常
    throw new Exception("just a test");
}
catch
{
    throw;
}
finally
{
    if(comm != null) comm.Close();
}
--------------------编程问答--------------------
using(SerialPort comm = new SerialPort())
{

   throw new Exception("just a test");
}

难道它就不重抛? --------------------编程问答--------------------
引用 9 楼 gomoku 的回复:
C# code
using(SerialPort comm = new SerialPort())
{

   throw new Exception("just a test");
}

难道它就不重抛?


是哦。看错了。这也会抛出异常的,没catch。 --------------------编程问答-------------------- 再调用的地方catch呗
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,