C#最后,finally被用来执行重要的代码,无论是否处理异常都要执行这些代码。必须在前面加上Catch或Try语句。
using System; public class ExExample { public static void Main(string[] args) { try { int a = 10; int b = 0; int x = a / b; } catch (Exception e) { Console.WriteLine(e); } finally { Console.WriteLine("Finally block is executed"); } Console.WriteLine("Rest of the code"); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-finally.html
来源:LearnFk无涯教程网
System.DivideByZeroException: Attempted to divide by zero. Finally block is executed Rest of the code
using System; public class ExExample { public static void Main(string[] args) { try { int a = 10; int b = 0; int x = a / b; } catch (NullReferenceException e) { Console.WriteLine(e); } finally { Console.WriteLine("Finally block is executed"); } Console.WriteLine("Rest of the code"); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-finally.html
来源:LearnFk无涯教程网
Unhandled Exception: System.DivideBy
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)