当前位置:网站首页>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;
}
}
边栏推荐
- Spark SQL common time functions
- The difference between Apple buy in and apple pay
- Debounce and throttle
- JS 同步、异步,宏任务、微任务概述
- 基于OpenCV和YOLOv3的目标检测实例应用
- JVM知识脑图分享
- Local cache --ehcache
- Args parameter parsing
- The development summary of the function of fast playback of audio and video in any format on the web page.
- Idea remotely submits spark tasks to the yarn cluster
猜你喜欢

ML - 语音 - 传统语音模型

ML - 自然语言处理 - 关键技术

小波变换--dwt2 与wavedec2

How to solve the login problem after the 30 day experience period of visual stuido2019

Spark partition operators partitionby, coalesce, repartition

Spark memory management mechanism new version

Application of C language array in Sanzi chess -- prototype of Queen n problem

NPM's nexus private server e401 E500 error handling record

打开虚拟机时出现VMware Workstation 未能启动 VMware Authorization Service

MySQL installation and configuration super detailed tutorial and simple database and table building method
随机推荐
CGO is realy Cool!
Application of object detection based on OpenCV and yolov3
ML - 图像 - 深度学习和卷积神经网络
MySQL installation and configuration super detailed tutorial and simple database and table building method
Iframe nested other website page full screen settings
Distributed principle - what is a distributed system
Overview of JS synchronous, asynchronous, macro task and micro task
ios 面试题
期货在线开户是否安全?去哪家公司手续费最低?
MySQL transactions and mvcc
伤透脑筋的CPU 上下文切换
vscode 插件篇收集
ML - natural language processing - Introduction to natural language processing
Redis elimination strategy list
JVM-垃圾收集器详解
任务、微任务、队列和调度(动画展示每一步调用)
PageHelper does not take effect, and SQL does not automatically add limit
NPM's nexus private server e401 E500 error handling record
JVM garbage collector details
什么是物联网