首页

C# 异常处理常用示例源码

c#

2020-8-26

除零异常、空引用、自定义异常示例,适合刚入门的同学学习

/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
		class MyException:ApplicationException
		{
			public MyException(String msg):base(msg)
			{
				HelpLink = "http://NotARealURL.Microsoft.com/help.html";
			}
		}
		public void ShowException(System.Exception ex)
		{
			string str;
			str = string.Format("Exception:\n\t{0}\n", ex.GetType().ToString());
			str  = string.Format("Message:\n\t{0}\n", ex.Message);
			str  = string.Format("Stack Trace:\n\t{0}\n", ex.StackTrace);
			str  = string.Format("Help Link:\n\t{0}\n", ex.HelpLink);
			MessageBox.Show(str);
		}
		// 除以 0 异常。
		private void button1_Click(object sender, System.EventArgs e)
		{
			int x = 0;
			try
			{
				// 产生异常。
				x = 10 / x;
			}
			catch(System.Exception ex)
			{
				ShowException(ex);
			}
		}
		// 无效对象异常。
		private void button2_Click(object sender, System.EventArgs e)
		{
			object a = null;
			try
			{
				MessageBox.Show(a.ToString());
			}
			catch(System.Exception ex)
			{
				ShowException(ex);
			}
		}
		// 自定义异常。
		private void button3_Click(object sender, System.EventArgs e)
		{
			try
			{
				throw(new MyException("这是我自己定义的异常。"));
			}
			catch(System.Exception ex)
			{
				ShowException(ex);
			}
		}
资源下载此资源下载价格为2D币(VIP免费),请先
资源文件列表
╥∞│ú┤ª└φ/App.ico , 1078
╥∞│ú┤ª└φ/AssemblyInfo.cs , 1846
╥∞│ú┤ª└φ/bin/Debug/Exception.exe , 8192
╥∞│ú┤ª└φ/bin/Debug/Exception.pdb , 17920
╥∞│ú┤ª└φ/Exception.csproj , 4371
╥∞│ú┤ª└φ/Exception.csproj.user , 1773
╥∞│ú┤ª└φ/Exception.sln , 914
╥∞│ú┤ª└φ/Exception.suo , 6656
╥∞│ú┤ª└φ/Form1.cs , 4582
╥∞│ú┤ª└φ/Form1.resx , 5315
╥∞│ú┤ª└φ/obj/Debug/Exception.exe , 8192
╥∞│ú┤ª└φ/obj/Debug/Exception.exe.incr , 1598
╥∞│ú┤ª└φ/obj/Debug/Exception.Form1.resources , 324
╥∞│ú┤ª└φ/obj/Debug/Exception.pdb , 17920
╥∞│ú┤ª└φ/obj/Debug/Exception.projdata , 6536
没有账号? 忘记密码?

社交账号快速登录