有些帖子询问这两者之间的区别是什么.
(为什么我还要提这个...)
但我的问题是不同的,我称之为"抛出前"在另一个错误的神像处理方法.
public class Program {
public static void Main(string[] args) {
try {
// something
} catch (Exception ex) {
HandleException(ex);
}
}
private static void HandleException(Exception ex) {
if (ex is ThreadAbortException) {
// ignore then,
return;
}
if (ex is ArgumentOutOfRangeException) {
// Log then,
throw ex;
}
if (ex is InvalidOperationException) {
// Show message then,
throw ex;
}
// and so on.
}
}
Run Code Online (Sandbox Code Playgroud)
如果try & catch用于Main,那么我会throw; …
有什么区别
try { }
catch
{ throw; }
Run Code Online (Sandbox Code Playgroud)
和
try { }
catch(Exception e)
{ throw e;}
Run Code Online (Sandbox Code Playgroud)
?
什么时候应该使用其中一个?
我有一个嵌套的try-catch代码,如下所示:
void A()
{
try
{
//Code like A = string(NULL) that throws an exception
}
catch(std::exception& ex)
{
cout<<"in A : " << ex.what();
throw ex;
}
}
void B()
{
try
{
A();
}
catch(std::exception& ex)
{
cout<<"in B : " << ex.what();
}
}
Run Code Online (Sandbox Code Playgroud)
运行后我得到了这个结果:
in A: basic_string::_M_construct null not valid
in B: std::exception
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,ex.what()在函数A中正常工作并告诉我正确的描述,但在B中ex.what()告诉我std::exception.为什么会这样?
我在函数A的catch子句中抛出了不同或错误的东西吗?如何抛出嵌套异常以便我可以在B中获得确切的异常描述?
如果一个候选人说他在C++中的知识是7/10并且你想用C++测试他的参考知识,你会问什么问题?
我想到了以下几点:
还有哪些其他问题可以更好地测试候选人对C++中引用的整体知识?
谢谢,
有时在代码中我看到抛出异常,其中使用了throw关键字而旁边没有表达式:
throw;
Run Code Online (Sandbox Code Playgroud)
它是什么意思,什么时候应该使用它?