try...catch...finally

4 本我 3周前 150次点击

简单理解为try(检查)catch(处理)finally(始终执行)

必须在连续的代码行中使用。其基本结构如下:

try

{

...

}

catch (exceptionType e) when (filterIsTrue)

{

...

}

finally

{

...

}

示例

using System;

using static System.Console;

using System.Diagnostics;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApplication1

{

class Program

{

static string[] eTypes = { "无","简单","索引","嵌套的索引","筛选"};

static void ThrowException(string exceptionType)

{

WriteLine($"ThrowException(\"{exceptionType}\")函数块");

switch (exceptionType)

{

case "无":

WriteLine("不抛出异常");

break;

case "简单":

WriteLine("抛出系统异常");

throw new System.Exception();

case "索引":

WriteLine("抛出System.IndexOutOfRange异常");

eTypes[5] = "错误";

break;

case "嵌套的索引":

try

{

WriteLine("ThrowException(\"嵌套的索引\")" + "到达函数内case是嵌套的索引的try块");

WriteLine("ThrowException(\"索引\")执行");

ThrowException("索引");

}

catch

{

WriteLine("ThrowException(\"嵌套的索引\")" + "已到达catch块");

throw;

}

finally

{

WriteLine("ThrowException(\"嵌套的索引\")到达finally块");

}

break;

case "筛选":

try

{

WriteLine("ThrowException(\"筛选\")" + "到达函数中case是筛选的try块");

WriteLine("ThrowException(\"索引\")执行");

ThrowException("索引");

}

catch

{

WriteLine("ThrowException(\"筛选\")"+"已到达函数内case筛选的catch块");

throw;

}

break;

}

}

static void Main(string[] args)

{

foreach (string eType in eTypes)

{

try

{

WriteLine("Main()已到达try");

WriteLine($"ThrowException(\"{eType}\")执行");

ThrowException(eType);

WriteLine("回到Main()还在try内");

}

catch (System.IndexOutOfRangeException e) when (eType == "筛选")

{

BackgroundColor = ConsoleColor.Red;

WriteLine($"已过滤System.IndexOutOfRangeException捕获块已到达。消息:\n \"{e.Message}\"");

ResetColor();

}

catch (System.IndexOutOfRangeException e)

{

WriteLine($"Main()System.IndexOutOfRangeException捕获块已到达。消息:\n\"{e.Message}\"");

}

catch

{

WriteLine("Main()通用补货快已到达");

}

finally

{

WriteLine("Main()终于到达最后的finally块了");

}

WriteLine();

}

ReadKey();

}

}

}

共 1 条评论
本我 [楼主] 3周前
0 

添加一条新评论

登录后可以发表评论 去登录