当前位置:网站首页>C # fine sorting knowledge points 12 exception handling (recommended Collection)
C # fine sorting knowledge points 12 exception handling (recommended Collection)
2022-07-25 15:35:00 【꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂】
1. The concept of abnormality
An exception is actually an event in which an error in a program interrupts the normal instruction flow .( You can think of an exception as any error condition that interrupts the normal program flow ).
Conditions that produce exceptions :
1: The file you want to open does not exist
2: Lost network connection
3: Call empty reference
4: except 0 abnormal
....
because C# It's object-oriented , All errors are encapsulated in exception objects
Once an error occurs , Will receive a specific exception object .
2. Exception class
.NET Framework All exceptions in the class library are derived from Exception class , Exceptions include system exceptions and application exceptions .
By default, all system exceptions are derived from System.SystemException, All application exceptions derive from System.ApplicationException.
System exception Generally unpredictable , For example, memory stack overflow , Empty object reference , permissions , Hardware read error, etc
Application exception Generally predictable , For example, the file object cannot be found , The value is out of range , Inconsistent data types, etc , Design , Processing logic can judge .
Common system exception classes
| Exception class | explain |
|---|---|
| System.OutOfMemoryException | use new Failed to allocate memory |
| System.StackOverflowException | Too many recursions 、 Too deep |
| System.NullReferenceException | The object is empty |
| Syetem.IndexOutOfRangeException | An array |
| System.ArithmaticException | The base class of arithmetic operation exception |
| System.DivideByZeroException | Divide by zero error |
3. exception handling
stay C# Exceptions and exceptions in language Processing statements namely try … catch… finally.
Use the meaning of keywords :
**try:** Used to check for exceptions that occur , And help send any possible exceptions .
**catch:** Dealing with errors in a more controlling way , There can be multiple catch Clause .
**finally:** Whether or not an exception was thrown ,finally All code blocks will be executed .
example :
class Program
{
static void Main(string[] args)
{
while(true)
{
try
{
// Try the following statement
Console.WriteLine(" Please enter divisor ( Input q sign out ):");
string str = Console.ReadLine(); // Exception may be thrown
if(str.Contains("q"))
{
break;
}
int num1 = int.Parse(str);// Exception may be thrown
Console.WriteLine(" Please enter the dividend :");
int num2 = int.Parse(Console.ReadLine());
Console.WriteLine(" The result of the calculation is :{0}", num1 / num2); // Exception may be thrown
}
catch(Exception e)
{
// Capture exception , Then process
Console.WriteLine(" Something goes wrong :{0}", e.Message);
}
finally
{
// Finish processing
}
}
}
}
4. Custom exception
Although in C# Many exception handling classes have been provided in the language , But in actual programming, we will still encounter some exception handling that are not involved .
For example, you want to put the validation of data into exception handling , That is, the entered age must be 18〜45, At this time, you need to customize the exception class to realize .
Custom exception classes It has to be Inherit Exception class
sentence :
class Exception class name :Exception
{
}
Throw your own exception , Use keywords throw .
Such as :
throw new Custom exception classes ( parameter list );
give an example :
Limit the range of numbers entered by the user to 1-100.
//InputException.cs
/// <summary>
/// Custom exception classes
/// Thrown when the input value does not meet the requirements
/// </summary>
class InputException:Exception
{
/// <summary>
/// Construction method
/// </summary>
/// <param name="inputNum"></param>
public InputException(int inputNum):base(string.Format(" abnormal : The input range is 1‐ 100, The value is {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(" The input is not a number ")
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(" Something goes wrong , Please try again !");
}
}
Console.WriteLine("Input Value :{0}", input);
}
static int GetUserInput()
{
Console.WriteLine(" Please enter a number :");
string str = Console.ReadLine();
int input = int.Parse(str)
if(input<1||input>100)
{
throw new InputException(input);
}
return input;
}
}
边栏推荐
- 2016 CCPC network trial c-change root DP good question
- MATLAB读取显示图像时数据格式转换原因
- 哪里有搭建flink cdc抽mysql数的demo?
- The difference between Apple buy in and apple pay
- 2021 Shanghai sai-d-cartland number variant, DP
- Idea护眼色设置
- Pytorch框架练习(基于Kaggle Titanic竞赛)
- 2019 Shaanxi provincial competition j-bit operation + greed
- 《图书馆管理系统——“借书还书”模块》项目研发阶段性总结
- Submarine cable detector tss350 (I)
猜你喜欢

Are you ready to break away from the "involution circle"?

Get the ask code corresponding to the key pressed by the keyboard

ML - natural language processing - Basics

Games101 review: linear algebra

Take you to create your first C program (recommended Collection)

Ml speech depth neural network model

JVM知识脑图分享

带你创建你的第一个C#程序(建议收藏)

分布式原理 - 什么是分布式系统

MATLAB读取显示图像时数据格式转换原因
随机推荐
Pytorch学习笔记--常用函数总结3
matlab--CVX优化工具包安装
Understanding the difference between wait() and sleep()
C # carefully sorting out key points of knowledge 11 entrustment and events (recommended Collection)
组件化和模块化
wait()和sleep()的区别理解
2019陕西省省赛K-变种Dijstra
ML - 自然语言处理 - 自然语言处理简介
2016CCPC网络选拔赛C-换根dp好题
MySQL优化总结二
本地缓存--Ehcache
2021上海市赛-H-二分答案
Pytorch学习笔记--常用函数总结2
理解“平均负载”
C#精挑整理知识要点10 泛型(建议收藏)
2021 Jiangsu race a Array line segment tree, maintain value range, Euler power reduction
4PAM在高斯信道与瑞利信道下的基带仿真系统实验
In depth: micro and macro tasks
JVM garbage collector details
Brain racking CPU context switching