定义一个继承Exception的类:
- class CustomException:Exception
- {
- /// <summary>
- /// 构造
- /// </summary>
- /// <param name="strMessage"></param>
- public CustomException(string strMessage)
- :base(strMessage)
- {
- }
- /// <summary>
- /// 构造
- /// </summary>
- /// <param name="strMessage"></param>
- /// <param name="ex"></param>
- public CustomException(string strMessage,Exception ex)
- : base(strMessage,ex)
- {
- }
- }
捕获异常:
- #region 自定义异常
- /// <summary>
- /// 自定义异常
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btnException_Click(object sender, EventArgs e)
- {
- try
- {
- throw new CustomException("自定义异常");
- }
- catch (CustomException ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- #endregion