C#程序异常捕获 try catch finally的特别说明
C#程序异常捕获 try catch finally的特别说明:
1、try语句要不跟catch,要不跟finally,至少要跟其中一个,不能一个都不跟;
2、try语句后不管catch如何执行,finnally最终都会被执行,且finnally属可选语句,不是必须的。
Expected catch or finally!
1 C# switch 错误捕获default:使用throw new ArgumentOutOfRangeException();不再需要前面的对monthName==""的if判断内容 2 3 static void Main(string[] args) 4 { 5 int month = int.Parse(Console.ReadLine()); 6 string strMonthName = monthName(month); 7 if (strMonthName == "") 8 { 9 Console.WriteLine("您您输入的月份不正确"); 10 } 11 12 Console.WriteLine(strMonthName); 13 } 14 static string monthName(int month) 15 { 16 switch (month) 17 { 18 case 1: 19 return "一月"; 20 case 2: 21 return "二月"; 22 default: 23 return ""; //此处可以直接使用throw new ArgumentOutOfRangeException(); 来捕获错误,需要删除前面的对monthName==“”的if判断内容 24 } 25 } 26 27 28 29 30 使用throw new ArgumentOutOfRangeException("月份不正确/Bad Month");之后的代码: 31 32 33 34 using System; 35 using System.Collections.Generic; 36 using System.Linq; 37 using System.Text; 38 39 namespace ConsoleApplication1 40 { 41 class Program 42 { 43 static void Main(string[] args) 44 { 45 int month = int.Parse(Console.ReadLine()); 46 try 47 { 48 49 string strMonthName = monthName(month); 50 // if (strMonthName == "") 51 // { 52 // Console.WriteLine("您您输入的月份不正确"); 53 // } 54 Console.WriteLine(strMonthName); 55 } 56 catch (ArgumentOutOfRangeException ex) 57 { 58 Console.WriteLine(ex.Message); 59 } 60 } 61 static string monthName(int month) 62 { 63 switch (month) 64 { 65 case 1: 66 return "一月"; 67 case 2: 68 return "二月"; 69 default: 70 // return ""; 71 throw new ArgumentOutOfRangeException("月份不正确 Bad Month"); 72 } 73 } 74 } 75 }