当前位置:网站首页>C#精挑整理知识要点12 异常处理(建议收藏)
C#精挑整理知识要点12 异常处理(建议收藏)
2022-07-25 15:23:00 【꧁小ۣۖิ鸽ۣۖิ子ۣۖิ꧂】
1.异常的概念
异常实际上是程序中错误导致中断了正常的指令流的一种事件.(你可以认为异常是任何中断正常程序流程的错误条件)。
产生异常的条件:
1:想打开的文件不存在
2:网络连接中断
3:调用空引用
4:除0异常
。。。。
由于C#是面向对象,所有所有的错误被封装在异常对象中
一旦错误发生,将接收到一个特定的异常对象。
2.异常类
.NET Framework 类库中的所有异常都派生于 Exception 类,异常包括系统异常和应用异常。
默认所有系统异常派生于 System.SystemException,所有的应用程序异常派生于System.ApplicationException。
系统异常一般不可预测,比如内存堆栈溢出,空对象引用,权限限制,硬件读取错误等等
应用程序异常一般可以预测,比如文件对象找不到啦,值不在范围内啦,数据类型不一致等等,设计,处理逻辑可以判断的。
常见的系统异常类
| 异常类 | 说明 |
|---|---|
| System.OutOfMemoryException | 用 new 分配内存失败 |
| System.StackOverflowException | 递归过多、过深 |
| System.NullReferenceException | 对象为空 |
| Syetem.IndexOutOfRangeException | 数组越界 |
| System.ArithmaticException | 算术操作异常的基类 |
| System.DivideByZeroException | 除零错误 |
3.异常处理
在 C# 语言中异常与异常处理语句即 try … catch… finally。
用到关键字其含义:
**try:**用于检查发生的异常,并帮助发送任何可能的异常。
**catch:**以控制权更大的方式处理错误,可以有多个 catch 子句。
**finally:**无论是否引发了异常,finally 的代码块都将被执行。
例:
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
{
//做结束处理
}
}
}
}
4.自定义异常
虽然在 C# 语言中已经提供了很多异常处理类,但在实际编程中还是会遇到未涉及的一些异常处理。
例如想将数据的验证放置到异常处理中,即判断所输入的年龄必须为 18〜45,此时需要自定义异常类来实现。
自定义异常类必须要继承 Exception 类
语句:
class 异常类名:Exception
{
}
抛出自己的异常,使用关键字throw 。
如:
throw new 自定义异常类(参数列表);
举例:
限制用户输入数字的范围为1-100。
//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)
{
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;
}
}
边栏推荐
- ML - natural language processing - Key Technologies
- matlab---错误使用 var 数据类型无效。第一个输入参数必须为单精度值或双精度值
- UIDocumentInteractionController UIDocumentPickerViewController
- C language function review (pass value and address [binary search], recursion [factorial, Hanoi Tower, etc.))
- Xcode added mobileprovision certificate file error: Xcode encoded an error
- spark分区算子partitionBy、coalesce、repartition
- The difference between Apple buy in and apple pay
- 你准备好脱离“内卷化怪圈”了吗?
- What is the Internet of things
- pageHelper不生效,sql没有自动加上limit
猜你喜欢
随机推荐
JVM-垃圾收集器详解
ML - 语音 - 语音处理介绍
How to update JSON values in the database?
分布式原理 - 什么是分布式系统
我的创作纪念日
How to finally generate a file from saveastextfile in spark
Instance Tunnel 使用
matlab 优化工具 manopt 安装
Spark sql 常用时间函数
Example of password strength verification
See a lot of blinking pictures on apps, especially the member page
BPSK调制系统MATLAB仿真实现(1)
Yan required executor memory is above the max threshold (8192mb) of this cluster!
Spark DF增加一列
The implementation process of inheritance and the difference between Es5 and ES6 implementation
Spark partition operators partitionby, coalesce, repartition
在网页上实现任意格式的音视频快速播放功能的开发总结。
4PAM在高斯信道与瑞利信道下的基带仿真系统实验
苹果内购和Apple Pay 的区别
你准备好脱离“内卷化怪圈”了吗?









