public class HonException:ApplicationException { public HonException() { // //TODO: 在此处添加构造函数逻辑 // } private string hong; public HonException(string hon) { hong = hon; HttpContext.Current.Response.Write("hong:" + hong+"<br>"); } public string Hong { get { return hong; } set { hong = value; } } }
protected void Page_Load(object sender, EventArgs e) { try { } catch (HonException h) { Response.Write(h.Hong + "<br>"); } catch (Exception ee) { Response.Write(ee.Message + "<br>"); } finally { Response.Write("over!<br>"); } }
protected void Page_Load(object sender, EventArgs e) { try { throw new HonException("hongdada"); } catch (HonException h) { Response.Write(h.Hong + "<br>"); } catch (Exception ee) { Response.Write(ee.Message + "<br>"); } finally { Response.Write("over!<br>"); } }
代码很简单,意思很明确,
自定义异常由自己抛出捕获
捕获异常以后进入catch,再执行finally
protected void Page_Load(object sender, EventArgs e) { try { throw new HonException("hongdada"); throw new HonException("hongdada2"); Response.Write("Last<br>"); } catch (HonException h) { Response.Write(h.Hong + "<br>"); } catch (Exception ee) { Response.Write(ee.Message + "<br>"); } finally { Response.Write("over!<br>"); } }
一个注意点:
在using中如果抛出错误,最后还是要执行释放对象的
public class Program { static void Main(string[] args) { try { new Hong(); using (new Hong()) { throw new Exception(); Console.WriteLine("using"); } } catch (Exception ee) { } Console.Read(); } } public class Hong : IDisposable { static Hong() { Console.WriteLine("1"); } public Hong() { Console.WriteLine("constructor"); } public void Dispose() { Console.WriteLine("2"); } }
如果是if
static void Main(string[] args) { try { new Hong(); if (true) { throw new Exception(); Console.WriteLine("if"); } } catch (Exception ee) { } Console.Read(); }
自定义异常要放在Exception上面
http://blog.csdn.net/zevin/article/details/6901489