|
try
{ ProcessString(s); }
catch (Exception e)
{ Console.WriteLine("{0} Exception caught.", e); } finally { }
============================================================
C#
|
class TryFinallyTest { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } } static void Main() { string s = null; // For demonstration purposes. try { ProcessString(s); } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } } } /* Output: System.ArgumentNullException: Value cannot be null. at TryFinallyTest.Main() Exception caught. * */ |
=================================================================
|
C#
|
class ThrowTest3 { static void ProcessString(string s) { if (s == null) { throw new ArgumentNullException(); } } static void Main() { try { string s = null; ProcessString(s); } // Most specific: catch (ArgumentNullException e) { Console.WriteLine("{0} First exception caught.", e); } // Least specific: catch (Exception e) { Console.WriteLine("{0} Second exception caught.", e); } } } /* Output: System.ArgumentNullException: Value cannot be null. at TryFinallyTest.Main() First exception caught. */ |
本文介绍了C#中使用try-catch进行异常处理的方法,并通过两个示例展示了如何捕获和处理不同类型的异常。
1万+

被折叠的 条评论
为什么被折叠?



