C#编程之C#基础(五)

时间:2019-11-18
本文章向大家介绍C#编程之C#基础(五),主要包括C#编程之C#基础(五)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天我们将以下错误和异常。我们知道程序出现错误的原因有些时候并不是程序员编写的应用程序的原因,有时应用程序会因为终端用户的操作而发生错误。

所以我们作为程序猿,就应该要避免类似这样的情况,做出预测可以出现的错误,应用程序应该如何处理这些错误与异常操作。

这里就要说到我们今天要讲解的C#处理错误的机制。

使用try-catch-finally捕获异常:

  1. try块包含的代码组成了程序的正常操作部分,但可能遇到某些严重的错误。
  2. catch块包含的代码处理各种错误,这些错误是try块中代码执行时遇到的。
  3. finally块包含的代码清理资源或执行要在try块或catch块末尾执行的其他操作。无论是否参数异常,finally块都会执行。
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Abnormal
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string userInput;
14             while(true)
15             {
16                 try
17                 {
18                     Console.WriteLine("Input a number between 0 and 5.");
19                     userInput = Console.ReadLine();
20                     if(userInput=="")
21                     {
22                         break;
23                     }
24                     int index = Convert.ToInt32(userInput);
25                     if(index<0||index>5)
26                     {
27                         throw new IndexOutOfRangeException("Input="+ userInput);
28                     }
29                     Console.WriteLine("your number is " + index);
30                 }
31                 catch(IndexOutOfRangeException ex)
32                 {
33                     Console.WriteLine("error:" + "please enter number between 0 and 5: " + ex.Message);
34                 }
35                 catch(Exception ex)
36                 {
37                     Console.WriteLine("error unknown throw: " + ex.Message);
38                 }
39                 catch
40                 {
41                     Console.WriteLine("some unkown exception has ocurred.");
42                 }
43                 finally
44                 {
45                     Console.WriteLine("thank you.");
46                 }
47             }
48         }
49     }
50 }

编译运行:

End

谢谢.

原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/11881222.html