ThrowAndThrowEx.cs

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	public static void Main()
	{
		// 目的:觀察 throw 與 throw ex 兩種寫法的差異。
		try 
		{
			StringToDate("123");
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex.ToString()); // 印出堆疊追蹤資訊
		}
		
		DateTime StringToDate(string input)
		{
			try
			{
				return Convert.ToDateTime(input);
			}
			catch (FormatException ex)
			{
				throw; // 這裡交替使用 throw 和 throw ex,然後觀察程式執行結果有何差異。
			}
		}
	}
}
;