[ASP.NET学习笔记之二十六]C#的异常处理

异常概述(Exception

异常(Exception

异常是当程序发生错误时产生的一种信号

.NET中,广泛使用,为什么?

Examples:

       divide-by-zero

       arithmetic overflow

       array access out of bounds

       null object reference

       file not found

异常类型

每种异常类型都是一个类

两种大分类

       System.SystemException

       System.ApplicationException

.NET中异常处理方式

.NET中异常处理方式

异常被对象所表现而不是错误代码

异常的产生是通过throwing一个该异常的对象实现的

异常的捕获是通过catch该异常的对象

命名上可以读出是哪类异常:

       ArithmeticException, DivideByZeroException, etc.

捕获异常try-catch

当代码段有可能发生异常的时候,我们应该把该代码段放置在try

捕获到异常后的处理方法放置到catch中。

try

{

s = << user’s input >>;

i = int.Parse(s); // if this fails, .NET throws exception…

}

catch

{

MessageBox.Show(“Invalid input, please try again.”);

return; // return now and give user another chance…

}

更好的解决方案

为每个可能的Exception定制解决方法

try

{

s = << user’s input >>;

i = int.Parse(s); // if this fails, .NET throws exception…

}

catch(FormatException)

{

MessageBox.Show(“Please enter a numeric value.”);

return;

}

catch(OverflowException)

{

MessageBox.Show(“Value is too large/small (valid range ” + int.MinValue +

... ” + int.MaxValue + “).”);

return;

}

catch(Exception ex)

{ // else something we didn’t predict has happened…

string msg;

msg = String.Format(“Invalid input./n/n[Error={0}]”, ex.Message);

MessageBox.Show(msg);

return;

}

异常处理的系统流程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值