异常处理示例

来源:互联网 发布:linux 文件读写 c程序 编辑:程序博客网 时间:2024/05/19 07:10
  1. using System;
  2. public class DataHouse
  3. {
  4.     public static void FindData( long ID) 
  5.     {
  6.         if( ID>0 && ID<1000)
  7.             Console.WriteLine( ID );
  8.         else
  9.             throw new DataHouseException("已到文件尾");
  10.     }
  11. }
  12. public class BankATM 
  13. {
  14.     public static void GetBalanceInfo( long  ID) 
  15.     {
  16.         try 
  17.         {
  18.             DataHouse.FindData(ID);
  19.         }
  20.         catch (DataHouseException e) 
  21.         {
  22.             throw new MyAppException("账号不存在",e);
  23.         }
  24.     }
  25. }
  26. public class DataHouseException:ApplicationException 
  27. {
  28.     public DataHouseException( string message )
  29.         :base(message)
  30.     {}
  31. }
  32. public class MyAppException:ApplicationException 
  33. {
  34.     public MyAppException (string message) 
  35.         base (message) 
  36.     {}
  37.     public MyAppException (string message, Exception inner)
  38.         base(message,inner)
  39.     {}   
  40. }
  41. public class Test 
  42. {
  43.     public static void Main() 
  44.     {
  45.         try 
  46.         {
  47.             BankATM.GetBalanceInfo( 12345L);
  48.         }
  49.         catch(Exception e) 
  50.         {
  51.             Console.WriteLine ("出现了异常: {0}", e.Message);
  52.             Console.WriteLine ("内部原因: {0}",e.InnerException.Message);
  53.         }
  54.     }
  55. }
0 0