C#中的异常捕捉(try)和异常处理(catch)
为了捕捉异常,代码要放到⼀个 try 块中(try 是 C# 关键字)。代码运⾏时它会尝试执⾏ try 块内的所有语句。如果没有任何语句产⽣⼀个异常,这些语句将⼀个接⼀个运⾏,直到全部完成。然⽽,⼀旦出现异常,就会跳出 try 块,并进⼊⼀个 catch 处理程序中执⾏。
在try块后紧接着写⼀个或多个 catch 处理程序(catch 也是 C# 关键字),⽤它们处理任何发⽣的错误。每个 catch 处理程序都负责捕捉并处理⼀种特定类型的异常,你可以在⼀个 try 块后⾯写多个 catch 处理程序。try 块中的任何⼀个语句造成错误,“运⾏时”(runtime)都会⽣成并抛出⼀个异常。然后“运⾏时”将检查 try 块之后的 catch 处理程序,将控制权移交给⼀个匹配的处理程序。
catch 处理程序结束之后,程序将从处理程序之后的第⼀个语句继续执⾏。
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TryAndCatch
7 {
8class Program
9    {
10static void Main(string[] args)
11        {
12try
13            {
14int a;
15string b;
16
17                Console.WriteLine("请输⼊⼀个整数: ");
18                b = Console.ReadLine(); // ReadLine() 获取到的是 string 类型的数据
19                a = int.Parse(b);      // int.Parse ⽅法将 string 类型转换 int 类型
20            }
21
22catch (Exception ex)    // 这是⼀个常规的 catch 处理程序,能捕捉⼀切异常
23            {
24                Console.WriteLine(ex);
25            }
26        }
27    }
28 }
由于 a 是 int 类型,所以要求输⼊的数据也要是 int 类型。此处输⼊ 1.0,类型不符合,所以 try 块在此处会捕捉到⼀个 FornatException ( 格式异常 ),然后 catch 块会处理这个异常,在这⾥具体的做法就是输出错误信息。
FornatException 属于 Exception。
运⾏后结果如下图所⽰:
将 try 和 catch 注释掉后代码如下:
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TryAndCatch
7 {
8class Program
9    {
10static void Main(string[] args)
11        {
12////try
13////{
14int a;
15string b;
16
17                Console.WriteLine("请输⼊⼀个整数: ");
18                b = Console.ReadLine();
19                a = int.Parse(b);
20////}
21
22////catch (Exception ex)
23////{
24////    Console.WriteLine(ex);
25////}
26        }
27    }
28 }
try catch的使用方法
由于没有进⾏异常捕捉和异常处理,所以运⾏后结果如下: