今日休假的最后一天,在寝室coding,想起java的项目有些纠结,就把C#的课本拿出来温习一下。练习的是两段异常处理的程序。
异常处理的方法一:可以在函数中处理异常并抛出,看下实例,最常见的除数为零的例子:
using System;
using System.Collections.Generic; using System.Linq; using System.Text;namespace 异常2
{ class ThrowExample { public void Div() { try { int x = 5; int y = 0; int z = x / y; Console.WriteLine(z); } catch (DivideByZeroException e) { throw new ArithmeticException("被除数为零"); } } public static void Main(string[] args) { try { ThrowExample te = new ThrowExample(); te.Div(); } catch (Exception e) { Console.WriteLine("Exception:{0}", e.Message); } Console.ReadKey(); } } } 这个实例是将异常处理放在div函数中,在mian函数中直接接收异常的处理。方法二:
using System;
using System.Collections.Generic; using System.Linq; using System.Text;namespace 异常
{ class ThrowExample { public void Div() { try { int x = 5; int y = 0; int z = x / y; Console.WriteLine(z); } catch (DivideByZeroException) { throw; } } public static void Main(string[] args) { try { ThrowExample te = new ThrowExample(); te.Div(); } catch (DivideByZeroException e) { Console.WriteLine("Exception:{0}", e.Message); } Console.Read(); } } } 这个是把异常在div函数中抛出,然后再在主函数中处理异常,两种方法均可实现异常的处理。