C#异常由类表示。C#中的异常类主要是直接或间接地从System.Exception类派生。从System.Exception类派生的某些异常类是System.ApplicationException和System.SystemException类。
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(); } } }
输出结果
Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in <a9b37148b4814c1a849bf4ee94fbe889>:0 Result: 0