C#异常处理

发布于:2022-12-31 ⋅ 阅读:(944) ⋅ 点赞:(0)

异常:程序执行时出现的问题,提供一种将程序控制权移交的能力

处理方法由以下四个关键字组成:

关键字 解释
try  标记一个将激活的异常代码块,其后至少跟一个catch块
catch 异常处理通过它来实现异常的捕获
finally 执行给定语句,不管异常是否抛出
throw 问题出现通过它来抛出一个异常

语法

        块中出现异常,利用try和catch关键字实现捕获,语法如下:

try
{
   // 引起异常的语句
}
catch( ExceptionName e1 )
{
   // 错误处理代码
}
catch( ExceptionName e2 )
{
   // 错误处理代码
}
catch( ExceptionName eN )
{
   // 错误处理代码
}
finally
{
   // 要执行的语句
}

C#中的异常类

        异常需要通过类来表示;主要派生于System.Exception 类

        System.ApplicationException 和 System.SystemException 类是派生于 System.Exception 类的异常类

System.ApplicationException 支持应用程序生成的异常,即用户自定义的异常都是该类的派生
System.SystemException 预定义好的,系统自带的异常基类

 System.SystemException 类的预定义的异常类:

异常类         描述
System.IO.IOException I/O 错误
System.IndexOutOfRangeException 超出数组索引的范围
System.ArrayTypeMismatchException 数组类型不匹配
System.NullReferenceException 空对象
System.DivideByZeroException 出现除以零操作
System.InvalidCastException 类型转换期间
System.OutOfMemoryException 空闲内存不足
System.StackOverflowException 栈溢出

异常处理   

        C#提供了结构化的异常处理方案(try && catch),使用此类块可将核心语句与错误语句有序的分离开。

        实例:出现System.DivideByZeroException除于零的操作

using System;
namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        DivNumbers()
        {
            result = 0;
        }
        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }

        }
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.division(25, 0);
            Console.ReadKey();
        }
    }
}

        division()方法是做num1与num2的除法操作,因为第二个参数为零-分母为零,程序会报错

继而,输出异常状态System.DivideByZeroException:Attempted to divide by zero.

输出结果:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.

at ...

Result: 0

创建用户自定义异常 

        自定义异常状态,派生自 ApplicationException 类

  实例:

using System;
namespace UserDefinedException
{
   class TestTemperature
   {
      static void Main(string[] args)
      {
         Temperature temp = new Temperature();
         try
         {
            temp.showTemp();
         }
         catch(TempIsZeroException e)
         {
            Console.WriteLine("TempIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}
public class TempIsZeroException: ApplicationException
{
   public TempIsZeroException(string message): base(message)
   {
   }
}
public class Temperature
{
   int temperature = 0;
   public void showTemp()
   {
      if(temperature == 0)
      {
         throw (new TempIsZeroException("Zero Temperature found"));
      }
      else
      {
         Console.WriteLine("Temperature: {0}", temperature);
      }
   }
}

public class TempIsZeroException: ApplicationException
        TempIsZeroException类派生自ApplicationException,

        用户自定义的异常处理方法TempIsZeroException(string message): base(message)

        其中,(string message): base(message)表示在TempIsZeroException中调用其父类带string类型的构造函数,由于子类不能直接继承父类的构造函数,故采用此方法实现。

程序运行流程:进try--方式异常-进catch-打印异常结果

        其中发生异常后,程序会把异常信息传输给e,通过e.Message方法将其输出

异常输出结果:

TempIsZeroException: Zero Temperature found

抛出对象

        异常是派生自System.Exception 类,可抛出一个对象。语法如下

Catch(Exception e)
{
   ...
   Throw e
}


网站公告

今日签到

点亮在社区的每一天
去签到