[C# Basic Detailed Explanation] (5) Exception Capture Try...Catch

In the running of C# program, there will inevitably be many abnormal events, which will prevent the program from continuing to run and increase difficulties for the user experience. If you want your program to be stronger, then you need to use the try-catch statement.

Abnormal means: there is no grammatical error, but during the running of the program, something goes wrong for some reason, so that the program can no longer run normally, also known as a bug.

The purpose of the try...catch statement is to solve the problem that the program cannot continue to execute when an error occurs.

grammar

try

{

//Executed code, which may have exceptions. Once an exception is found, it immediately jumps to catch execution. Otherwise, the contents of the catch will not be executed

}

//no other code between try and catch

catch

{

//Unless an exception occurs in the execution code in try, the code here will not be executed

}

finally

{

//It will be executed no matter what the situation, including the use of return in try catch, it can be understood that as long as try or catch is executed, finally will be executed

}

try -- means "try it out"
catch -- means "catch",
finally -- there can be none or only one.

If there is no mistake, you will not be able to catch it, and only if there is a mistake can you catch and deal with it.

Note: After the code inside the catch {...} curly braces is executed, the following code will continue to be executed. If you want to terminate the program, use return.

Exception catch instance
int number = 0;//声明一个int类型的变量并赋初值为0
Console.WriteLine("请输入一个数字");
try//如果用户输入的是数字执行try内代码
{
    number = int.Parse(Console.ReadLine());
    Console.WriteLine(number * 2);
}
catch//输入的内容不能转换成数字
{
    Console.WriteLine("你输入的字符串不能转换成数字");
}
Console.ReadKey();
bool type practice
int number = 0;
bool b = true;//声明一个bool类型的变量 初值赋值为true
Console.WriteLine("请输入一个数字");
try
{
    number = int.Parse(Console.ReadLine());
}
catch
{
    Console.WriteLine("你输入的字符串不能转换成数字");
    b = false;
}

if (b)
{
    Console.WriteLine(number * 2);
}
Console.ReadKey();

Guess you like

Origin blog.csdn.net/Y1RV1NG/article/details/129539420