64,643
社区成员
发帖
与我相关
我的任务
分享
int fun3()
{
return -1;
}
void fun2()
{
fun3()
}
void fun1()
{
fun2()
}
假设以上三段代码分别是三个不同的人写的。
fun3返回-1表示出错了。
但是如果fun1想知道出错了,需要fun2里面return fun3(),而不能直接调用fun3()就没有了。
直接调用fun3()就导致了错误码的丢失,上层逻辑由于写fun2的人的疏忽,不知道到底是什么错。
但是如果是异常机制,fun3抛出异常,fun2疏忽了,没有try,catch,这个异常不会丢,会继续抛到fun1。
也就是fun2不想关心出了什么错,就可以不关心。
fun1想关心,也不会因为fun2的不关心而导致关心不到,鞭长莫及。
异常怎么用:
尽量不用,就像C里面的goto一样,本质都是跳转。
参考《代码大全》中的一段话:仅在其他编码实践方法无法解决的情况下,才使用异常
http://www.geeksforgeeks.org/exception-handling-c/
MyData md;
try {
// Code that could throw an exception
md = GetNetworkResource();
}
catch (const networkIOException& e) {
// Code that executes when an exception of type
// networkIOException is thrown in the try block
// ...
// Log error message in the exception object
cerr << e.what();
}
catch (const myDataFormatException& e) {
// Code that handles another exception type
// ...
cerr << e.what();
}
// The following syntax shows a throw expression
MyData GetNetworkResource()
{
// ...
if (IOSuccess == false)
throw networkIOException("Unable to connect");
// ...
if (readError)
throw myDataFormatException("Format error");
// ...
}