c#异常处理的机制

1.异常处理的基本语法

int x=0;

try
{
int y=100/x;
}
catch(Exception e) //捕获异常 Ststem.Exception
{
    Console.Writeline(e.Message); //打印异常消息 或者处理异常的操作
}
finally // 不管是否捕捉到异常  都要执行
{
    Console.Writeline("不管怎么样,都打印");
}
// 放在finally后不执行 
throw new NullReferenceException().//扔出异常

2.异常类

System.IO.IOException   //处理I/O错误
System.IndexOutOfRangeException  //处理当方法只想超出范围的数组索引时生成的错误
System.ArrayTypeMismatchException  //处理当数组类型不匹配时生成的错误
System.NullReferenceException    //报空
System.DivideByZeroException  //处理当除以零是生成的错误
System.InvalidCastException    // 处理在类型转换期间生成的错误
System.OutOfMemoryException    // 处理空闲内存不足生成的错误
System.StackOverflowException  // 处理栈溢出生成的错误

3.创建用户自定义异常

用户自定义的异常类需要继承 ApplicationException

class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature(); // 实例化一个温度类  
         try
         {
            temp.showTemp();//温度类中 当温度为零 会出现异常TempIsZeroException
         }
         catch(TempIsZeroException e) // 捕捉到异常
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message); // 打印异常信息
         }
         Console.ReadKey();
      }
   }

public class TempIsZeroException : ApplicationException // 继承 ApplicationException
{
    public TempIsZeroException (string message):base (message)  // 构造方法 
    {   
    }
}

public class Temperature 
{
    int temperature = 0;
    public void showTemp()
    {
        if(temperature==0) 
        {
         throw (new TempIsZeroException("Zero is found"));   // 定义 异常信息
        }
        else
        {
            Console.WriteLine("Temperature:{0}",temperature); //无异常  输出 温度
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_53803837/article/details/126112200