这里主要说明的是try catch过程中,程序的执行流程以及需要注意的问题。
这里使用2个函数的调用来体现多层函数的调用和异常的使用。TestA() 调用TestB().
使用的异常是格式异常,int.parse() 解析非整数数字字符串会由异常,格式不正确。
流程1:
不使用try catch语句,如果遇到异常则会导致程序停止。
static int TestB() {
int a = int.Parse("oo");
return a;
}
public static void TestA() { int ret = TestB(); MessageBox.Show(ret.ToString());
}
|
流程2:
这个情况就是使用了try catch 结构,但是并没有处理错误。程序正常运行,结果为0.
static int TestB() { int a = 0; try { a = int.Parse("oo");
} catch {
} return a;
}
public static void TestA() { int ret = TestB(); MessageBox.Show(ret.ToString());
} |
流程3:
使用了try catch 结构,捕捉了异常,但是解析异常没有和IOException 异常类型匹配,导致程序没有进入到catch区域,直接在当前区域停止程序。这里特意使用了IOException的类型,如果使用Exception基类类型,那么所有的异常类型都是匹配的,就不糊出现匹配不到的情况。
static int TestB() { int a = 0; try { a = int.Parse("oo"); } catch(IOException ex) { a = -1; }
return a;
}
public static void TestA() { int ret = TestB(); MessageBox.Show(ret.ToString());
}
|
流程4:
在catch语句中接收异常,并且处理异常,把异常记录日志或者通过参数返回出来。
static int TestB(ref string str) { int a = 0; try { a = int.Parse("oo"); } catch(Exception ex) { str = ex.Message; a = -1; }
return a;
}
public static void TestA() { string str = ""; int ret = TestB(ref str); if (str == "") { MessageBox.Show(ret.ToString()); } else { MessageBox.Show(str); } } |
流程5:
TestB遇到异常抛出,不对异常进行处理,TestA进行try catch处理。
这时候,TetsB中运行到cacht中,throw 之后不会在运行return a语句了。
这种情况表示异常很严重,TestB是不可能正常运行。只有解决异常,TestB才能正常运行。
static int TestB() { int a = 0; try { a = int.Parse("oo"); } catch(Exception ex) { throw new Exception("解析字符串异常",ex); }
return a;
}
public static void TestA() {
try { int ret = TestB(); } catch(Exception ex) { MessageBox.Show(ex.Message); }
} |
流程6:
TestB进行try cacht的抛出异常,testA不对异常进行处理。
结果就是程序停止运行,停在抛出异常的地方。
static int TestB() { int a = 0; try { a = int.Parse("oo"); } catch(Exception ex) { throw new Exception("解析字符串异常",ex); }
return a;
}
public static void TestA() {
int ret = TestB();
}
|
总结:
这里对异常处理的几种场景进行讨论,流程1和流程2基本就是不对异常进行处理,完全忽略对异常的处理。流程3是故意设计的,实际很少出现,只是说明当try发生异常的时候确实要和catch后的exception对象进行类型比较的。
流程6也是不对异常进行处理,流程4是对异常进行处理,流程5的抛到上一层进行处理实际中都有这种场景。
Message:异常消息,StakTrace:异常的调用信息,Source:发生异常的来源。