C#异常处理

  1. 异常
     语法上没有错误,在程序运行过程中,由于某些原因程序出现了错误,不能正常运行。
     
     使用 try-catch 进行异常捕获。
     
     另一个异常处理的关键字 finally
     用法:如果存在finally代码块,那么finally中的代码一定会被执行
 
语法:
try
{
     可能会出现异常的代码;
}
catch
{
     出现异常后要执行的代码;
}
执行过程:
     如果try中的代码没有出现异常,那么catch中的代码不会执行。
     如果try中的代码出现异常,try里后的代码都不会执行了;而是直接跳到catch中执行代码。
 
  1. 变量的作用域
     变量的作用域就是你能够使用到这个变量的范围。
 
  1. 代码展现
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _5异常处理
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //语法上没有错误,在程序运行过程中,由于某些原因程序出现了错误,不能正常运行。
14             Console.WriteLine("请输入一个数字");
15             int number = 0;//声明
16             bool b = true;
17             try
18             {
19                 number = Convert.ToInt32(Console.ReadLine());//赋值
20                 //Console.WriteLine(number * 2);//使用
21             }
22             catch (Exception)
23             {
24                 Console.WriteLine("输入错误");
25                 b = false;
26             }
27             //让代码满足某些条件去执行的话,使用bool类型
28             if (b == true)
29             {
30                 Console.WriteLine(number * 2);//使用
31             }
32 
33             Console.ReadKey();
34         }
35     }
36 }

 

posted @ 2016-10-09 21:52  智博的日常  阅读(1693)  评论(0编辑  收藏  举报