- 普通获取异常的规则:
- try
- {
- test();
- }
- catch (Exception ex)
- {
- //自定义异常
- throw new Exception("出错啦!", ex);
- }
- finally
- {
- //无论是否异常都会执行处理
- }
- 其实catch 了异常后,如果不处理,直接写 throw 即可,不用 throw ex; 示例如下:
- try
- {
- test();
- }
- catch
- {
- //异常处理
- throw;
- }
- 而对于无须异常处理的情况,写法如下:
- try
- {
- test();
- }
- finally
- {
- //释放资源
- }
- 这个经测试也是正确的!以前真不知道这样也行。但会在抓取异常的上部分报错;
- try
- {
- try
- {
- int sum = 3 / int.Parse(TextBox1.Text);
- Response.Write(sum);
- }
- //catch (Exception)
- //{
- // throw;
- //}
- finally
- {
- Response.Write("hello:");
- }
- }
- catch (Exception ex)
- {
- Response.Write(ex.Message.ToString());
- }
- 被除数为0的时候依然会执行:Response.Write("hello:");
- 输出:hello:试图除以零。
- //该片段来自于http://www.codesnippet.cn/detail/0508201614898.html
来源: http://www.codesnippet.cn/detail/0508201614898.html