【Unity|C#】(2)——异常处理

【学习资料】

        > 在线文档

            官方文档:https://docs.microsoft.com/zh-cn/dotnet/csharp/

            菜鸟教程:https://www.runoob.com/csharp/csharp-tutorial.html

        > 视频教程

            腾讯学院、Siki学院


 【笔记】

try 一个 try 块标识了一个将被激活的特定的异常的代码块。后跟一个或多个 catch 块。
catch 程序通过异常处理程序捕获异常。catch 关键字表示异常的捕获。
finally

finally 块用于执行给定的语句,不管异常是否被抛出都会执行

例如,如果您打开一个文件,不管是否出现异常文件都要被关闭。

throw 当问题出现时,程序抛出一个异常。使用 throw 关键字来完成。
  • C#中内置的异常类型
    • C# 中的异常类主要是直接或间接地派生于 System.Exception 类。System.ApplicationException System.SystemException 类是派生于 System.Exception 类的异常类。
    • System.ApplicationException :支持由应用程序生成的异常。所以程序员定义的异常都应派生自该类。
    • System.SystemException        :是所有预定义的系统异常的基类。
    • 下表列出了一些派生自 Sytem.SystemException 类的预定义的异常类:

  • 举个例子
    • int result = 0;
      int num1 = 25;
      int num2 = 0;
      try
      {
          result = num1 / num2;
      }
      catch (DivideByZeroException e) // 捕获除以0的异常
      {
          Debug.Log(string.Format("Exception caught: {0}", e));
      }
      finally // 不管是否异常,都会执行
      {
          Debug.Log(string.Format("Result: {0}", result));
      }
      
      // 输出结果
      // Exception caught: System.DivideByZeroException: Attempted to divide by zero.
      //  at ......
      // Result: 0
  • 用户自定义异常类型
    • 用户自定义的异常类是派生自 ApplicationException
    • // 自定义异常
      public class TempIsZeroException : ApplicationException
      {
          public TempIsZeroException(string message) : base(message)
          {
          }
      }
      namespace UserDefinedException
      {
          class TestTemperature
          {
              public static void ShowTemp(int temperature)
              {
                  if (temperature == 0)
                  {
                      // 抛出自定义异常 TempIsZeroException
                      throw (new TempIsZeroException("Zero Temperature found"));
                  }
              }
              static void Main(string[] args)
              {
                  try
                  {
                      ShowTemp(0);
                  }
                  catch (TempIsZeroException e) // 捕获自定义异常
                  {
                      Console.WriteLine("TempIsZeroException: {0}", e.Message);
                  }
                  Console.ReadKey();
              }
          }
      }

猜你喜欢

转载自www.cnblogs.com/shahdza/p/12234163.html