zoukankan      html  css  js  c++  java
  • 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.

    谢谢.

  • 相关阅读:
    java第九周上机
    安卓-计算器
    安卓第四周作业
    第十五周作业
    第十三周作业
    第十三周上机作业
    第十二周作业
    第十二周上机作业
    第十一周作业
    第十一周上机作业
  • 原文地址:https://www.cnblogs.com/lumao1122-Milolu/p/11881222.html
Copyright © 2011-2022 走看看