關於C#異常處理!

來源:互聯網
上載者:User
 1 using System;
 2 
 3 namespace ConsoleApplication2
 4 {
 5  /// <summary>
 6  /// Class1 的摘要說明。
 7  /// </summary>
 8  class Class1
 9  {
10   static string[] eTypes={"none","simple","index","nested index"};
11   [STAThread]
12   static void Main(string[] args)
13   {
14    foreach(string eType in eTypes)
15    {
16     try
17     {
18      Console.WriteLine("Main() try block reached.");
19      Console.WriteLine("ThrowException(\"{0}\") called.",eType);
20      ThrowException(eType);
21      Console.WriteLine("Main() try block continues.");
22     }
23     catch(System.IndexOutOfRangeException e)
24     {
25      Console.WriteLine("Main() System.IndexOutOfRangeException catch "+
26       " block reched.Message:\n\"{0}\"",e.Message);
27     }
28     catch
29     {
30      Console.WriteLine("Main() general catch block reached.");
31     }
32     finally
33     {
34      Console.WriteLine("Main() finally block reached.");
35     }
36     Console.WriteLine();
37    }
38   }
39   static void ThrowException(string exceptionType)
40   {
41    Console.Write("ThrowException(\"{0}\")reached.",exceptionType);
42    switch(exceptionType)
43    {
44     case "none":
45      Console.WriteLine("Not throwing an exception.");
46      break;
47     case "simple":
48      Console.WriteLine("Throwing System.Exception.");
49      throw(new System.Exception());
50      break;
51     case "index":
52      Console.WriteLine("Throwing System.IndexOutOfRangeexception.");
53      eTypes[4]="error";
54      break;
55     case "nested index":
56      try
57      {
58       Console.WriteLine("ThrowException(\"nested index\"):"+"tyr block reached.");
59       Console.WriteLine("ThrowException(\"index\")called.");
60       ThrowException("index");
61      }
62      catch
63      {
64       Console.WriteLine("ThrowException(\"nested index\")general"+" catch block reached.");
65      }
66      finally
67      {
68       Console.WriteLine("ThrowException(\"nested index\")finally"+"block reached.");
69      }
70      break;
71    }
72   }
73  }
74 }
75 
76 此異常的處理說明,異常產生後,如果在當前未做Try處理,則會返到上一級,如果還未做,則返回上一級的上一級.以此類推.如果被任意一級Catch到,則上一級不會再得到.
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.