这篇文章可能与有关 C++ 异常的常见问题有点不同。
在 C++ 中,如何处理用户输入错误,具体来说,我的意思是当提示用户输入整数并输入浮点数或字符串/字符时,反之亦然。您知道,就像有人在被提示输入年龄时输入自己的名字一样。
我基本上是在谈论 C++ 中的内容与 Python 中的内容相同,例如:
try:
[code to prompting user for an integer.]
exception ValueError:
[code to run if exception is thrown.]
Run Code Online (Sandbox Code Playgroud)
如果你们中的一个很棒的人有空闲时间以初学者能够理解的方式向我解释这一点,我将非常感激。
谢谢。
try catch 的基本示例如下:
try
{
// code that throws an exception
}
catch(...)
{
// exception handling
}
Run Code Online (Sandbox Code Playgroud)
请注意,这三个点对于捕获所有异常完全有效,尽管您不知道捕获了“什么”。这就是为什么您应该更喜欢在括号中指定类型。
要捕获的异常可以是从 int 开始并以指向从异常类派生的对象的指针结束的任何类型。这个概念非常灵活,但是您必须知道可能会发生什么异常。
这可能是一个更具体的示例,使用 std::excpetion: 注意通过引用捕获。
try
{
throw std::exception();
}
catch (const std::exception& e)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
下一个示例假设您使用 MFC 库编写 C++。它澄清了 CException catch 被执行,因为 CFileException 派生自 CException。如果不再需要,CException 对象将自行删除。除非您的异常派生自 CException,否则您不应该抛出指针并坚持上面的示例。
try
{
throw new CFileException();
}
catch (CException* e)
{
// CFileException is caught
}
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的一点也很重要:您可以定义多个 catch 块来捕获不同的异常:
try
{
throw new CFileException();
}
catch (CMemoryException* e)
{
// ignore e
}
catch (CFileException* e)
{
// rethrow exception so it gets handeled else where
throw;
}
catch (CException* e)
{
// note that catching the base class should be the last catch
}
Run Code Online (Sandbox Code Playgroud)