检查用户输入的是否是一个0-5中间的数字: 多重catch块
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ExceptionDemo { class Program { static void Main(string[] args) { string userInput; while (true) { try { Console.Write("Input a number between 0 and 5" + "(or just hit return to exist)>"); userInput = Console.ReadLine(); if (userInput == "") break; int index = Convert.ToInt32(userInput); if (index < 0 || index > 5) throw new IndexOutOfRangeException("You typed in " + userInput); Console.WriteLine("Your number was " + index); } catch (IndexOutOfRangeException ex) { Console.WriteLine("Exception: " + "Number should between 0 and 5." + ex.Message); } catch (Exception ex) { Console.WriteLine("An exception was thrown. Message was: {0}" + ex.Message); } catch { Console.WriteLine("Some other exception has occured"); } finally { Console.WriteLine("Thank you"); } } } } }
当输入的是非0-5之间的数字的时候,抛出的第一个异常,如果是一个字符串,抛出的第二个异常。第三个异常不带参数,这个catch块处理的是其他没有用C#编程的代码。
下面这个是MSDN一个try…finally的异常处理
static void CodeWithCleanup() { System.IO.FileStream file = null; System.IO.FileInfo fileInfo = null; try { fileInfo = new System.IO.FileInfo("C:\\file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); } catch (System.Exception e) { System.Console.WriteLine(e.Message); } finally { if (file != null) { file.Close(); } } }