using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CSharpExceptionHandlingLab
{
public class TempIsZeroException : Exception
{
public TempIsZeroException(string message) : base(message)
{
}
}
public class LegacyAppTempException : ApplicationException
{
public LegacyAppTempException(string message) : base(message)
{
}
}
internal class DivNumbers
{
private int result;
public bool FinallyExecuted { get; private set; }
public bool CaughtDivideByZero { get; private set; }
public DivNumbers()
{
result = 0;
}
public int Division(int num1, int num2)
{
FinallyExecuted = false;
CaughtDivideByZero = false;
result = 0;
try
{
result = num1 / num2;
}
catch (DivideByZeroException)
{
CaughtDivideByZero = true;
}
finally
{
FinallyExecuted = true;
}
return result;
}
}
internal class TemperatureSensor
{
private int temperature;
public TemperatureSensor(int value)
{
temperature = value;
}
public string CheckTemp()
{
if (temperature == 0)
{
throw new TempIsZeroException("Zero Temperature found");
}
return string.Format("Temperature: {0}", temperature);
}
}
internal class Program
{
private static void InnerFault()
{
throw new InvalidOperationException("inner-boom");
}
private static void RethrowPreserve()
{
try
{
InnerFault();
}
catch (InvalidOperationException)
{
throw;
}
}
private static void RethrowReset()
{
try
{
InnerFault();
}
catch (InvalidOperationException ex)
{
throw ex;
}
}
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: try/catch/finally divide by zero
DivNumbers div = new DivNumbers();
int rErr = div.Division(25, 0);
bool errCaught = div.CaughtDivideByZero;
bool errFin = div.FinallyExecuted;
int rOk = div.Division(25, 5);
bool okCaught = div.CaughtDivideByZero;
bool okFin = div.FinallyExecuted;
string actual1 = string.Format("err={0}/{1}/{2};ok={3}/{4}/{5}", rErr, errCaught, errFin, rOk, okCaught, okFin);
cases.Add(CaseJson(
"try_catch_finally_divide_by_zero",
"Verify try/catch handles DivideByZeroException and finally executes on both exception and normal paths",
"err=0/True/True;ok=5/False/True",
actual1
));
// Case 2: custom exception & hierarchy
string caughtMsg = "";
try
{
new TemperatureSensor(0).CheckTemp();
}
catch (TempIsZeroException ex)
{
caughtMsg = ex.Message;
}
string okMsg = new TemperatureSensor(25).CheckTemp();
bool legacyIsEx = typeof(LegacyAppTempException).IsSubclassOf(typeof(ApplicationException))
&& typeof(ApplicationException).IsSubclassOf(typeof(Exception));
bool modernIsEx = typeof(TempIsZeroException).IsSubclassOf(typeof(Exception));
string actual2 = string.Format("{0}|{1}|legacy={2}|modern={3}", caughtMsg, okMsg, legacyIsEx, modernIsEx);
cases.Add(CaseJson(
"custom_exception_hierarchy",
"Verify custom exception throwing/catching and Exception vs ApplicationException inheritance",
"Zero Temperature found|Temperature: 25|legacy=True|modern=True",
actual2
));
// Case 3: rethrow stack trace preservation & multi-catch ordering
bool preserveHasInner = false;
try { RethrowPreserve(); }
catch (InvalidOperationException ex)
{
preserveHasInner = ex.StackTrace != null && ex.StackTrace.IndexOf("InnerFault", StringComparison.Ordinal) >= 0;
}
bool resetLosesInner = false;
try { RethrowReset(); }
catch (InvalidOperationException ex)
{
resetLosesInner = ex.StackTrace != null && ex.StackTrace.IndexOf("InnerFault", StringComparison.Ordinal) < 0;
}
string multiMatch = "";
try { throw new ArgumentNullException("p"); }
catch (ArgumentNullException) { multiMatch = "specific"; }
catch (ArgumentException) { multiMatch = "base"; }
string actual3 = string.Format("preserve={0};resetNoInner={1};multi={2}", preserveHasInner, resetLosesInner, multiMatch);
cases.Add(CaseJson(
"rethrow_stack_trace_preservation",
"Verify bare throw preserves original stack frame while throw ex resets it, plus specific-before-general catch order",
"preserve=True;resetNoInner=True;multi=specific",
actual3
));
// Case 4: predefined SystemException subclasses
List<string> triggered = new List<string>();
try { throw new IOException("io-sim"); } catch (IOException) { triggered.Add("IO"); }
try { int[] a = new int[1]; int x = a[3]; Console.Write(x); } catch (IndexOutOfRangeException) { triggered.Add("Index"); }
try { object[] arr = new string[1]; arr[0] = 42; } catch (ArrayTypeMismatchException) { triggered.Add("ArrayType"); }
try { string s = null; int len = s.Length; Console.Write(len); } catch (NullReferenceException) { triggered.Add("NullRef"); }
try { int z = 0; int y = 10 / z; Console.Write(y); } catch (DivideByZeroException) { triggered.Add("DivZero"); }
try { object o = "abc"; int n = (int)o; Console.Write(n); } catch (InvalidCastException) { triggered.Add("Cast"); }
bool oomSys = typeof(OutOfMemoryException).IsSubclassOf(typeof(SystemException));
bool soSys = typeof(StackOverflowException).IsSubclassOf(typeof(SystemException));
string actual4 = string.Join(",", triggered.ToArray()) + string.Format(";OOM={0};SO={1}", oomSys, soSys);
cases.Add(CaseJson(
"system_exception_types_runtime",
"Verify 6 catchable SystemException subclasses at runtime and confirm OutOfMemoryException/StackOverflowException derive from SystemException",
"IO,Index,ArrayType,NullRef,DivZero,Cast;OOM=True;SO=True",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
入口文件:projects/csharp-exception-handling-lab/ExploreExceptionHandling.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreExceptionHandling.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1333.zip