C#中的异常处理
一、异常的概念
异常是在程序执行期间出现的问题。
产生异常的条件: 1:想打开的文件不存在 2:网络连接中断 3:调用空引用4:除0异常 等等
C# 中的异常是对程序运行时出现的特殊情况的一种响应。
- 异常类
C# 异常是使用类来表示的。
系统异常一般不可预测,比如内存堆栈溢出,空对象引用,权限限制,硬件读取错误等等
应用程序异常一般可以预测,比如文件对象找不到啦,值不在范围内啦,数据类型不一致等等,设计,处理逻辑可以判断的。
常见的异常类如下图所示:
Exception
SystemException
OutOfmemoryException
IOException
NullReferenceException
ApplicationException
常见的系统异常类如下表所示:
异常类 | 说明 |
System.OutOfMemoryException | 用 new 分配内存失败 |
System.StackOverflowException | 递归过多、过深 |
System.NullReferenceException | 对象为空 |
Syetem.IndexOutOfRangeException | 数组越界 |
System.ArithmaticException | 算术操作异常的基类 |
System.DivideByZeroException | 除零错误 |
三、异常处理
在 C# 语言中异常与异常处理语句即 try ... catch... finally...throw。
在上述异常处理的形式中所用到关键字其含义如下:
try:用于检查发生的异常,并帮助发送任何可能的异常。后跟一个或多个 catch 块。
catch:以控制权更大的方式处理错误,可以有多个 catch 子句。
finally:无论是否引发了异常,finally 的代码块都将被执行。
throw:当问题出现时,程序抛出一个异常。使用 throw 关键字来完成。
举例如下:
Class Program
{
Static void Main(string[] args)
{
While (true)
{
Try
{
//尝试执行下列语句
Console.WriteLine(“请输入除数(输入q退出): ”);
String str = Console.ReadLine(); //可能会抛出异常
If (str.Contains(“q”))
{
Break;
}
Int num1=int.Parse(str); //可能会抛出异常
Console.WriteLine(“请输入被除数;”);
Int num2=int.Parse(Console.ReadLine());
Console.WriteLine(“计算结果:{0}”,num1 / num2); //可能会抛出异常
}
Catch(Exception e)
{
// 捕获异常,然后处理
Console.WriteLine("发生异常:{0}", e.Message);
}
finally
}
//做结束处理
}
}
四、自定义异常
自定义异常类必须要继承 Exception 类。
自定义异常的语句如下:
class 异常类名 :Exception
{
}
抛出自己的异常,使用关键字throw 。
语句如下:
1throw new 自定义异常类(参数列表);
自定义异常类举例如下:
//InputException.cs
/// <summary>
/// 自定义异常类
/// 当输入值不满足要求时抛出
/// </summary>
class InputException:Exception
{
/// <summary>
/// 构造方法
/// </summary>
/// <param name="inputNum"></param>
public InputException(int inputNum):base(string.Format("异常:输入范围为1‐100,值为{0}",inputNum))
{
}
}
class Program
{
static void Main(string[] args)
{
int input = 0;
while(true)
{
Try
{
input = GetUserInput();
break;
}
catch(InputException ex)
{
Console.WriteLine(ex.Message);
}
catch(FormatException)18
{
Console.WriteLine("输入的内容不是数字");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("发生异常,请重试!");
}
}
Console.WriteLine("Input Value :{0}", input);
}
static int GetUserInput()
{
Console.WriteLine("请输入一个数字:");
string str = Console.ReadLine();
int input = int.Parse(str);
if (input < 1 || input > 100)
{
throw new InputException(input);
}
return input;
}
}
五、抛出对象
如果异常是直接或间接派生自 System.Exception 类,你可以抛出一个对象。你可以在 catch 块中使用 throw 语句来抛出当前的对象,如下所示:
Catch(Exception e)
{ ...
Throw e
}