<C >在例外處理中,是否需要知道什么例外以及例外會發生在哪里?你能寫一個代碼來列印并通知我們程式中的某個地方發生了例外。我的意思是我有一個程式,我不知道是否會發生例外,如果發生例外,它會列印出來通知我們。
uj5u.com熱心網友回復:
例外處理是你應該設計的東西,事實上它與 RAII ( https://en.cppreference.com/w/cpp/language/raii )一起作業得很好。(Notr 在使用例外的嵌入式平臺上,由于一些運行時開銷而不那么流行)。我個人喜歡例外的地方在于它將錯誤處理與正常的程式流程分開(如果正確,則幾乎沒有任何 if then else 檢查)
// Exception handling should be part of your overal design.And many standard library functions can throw exceptions, It is always up to you where you handle them.
#include <iostream>
#include <string>
#include <stdexcept>
int get_int_with_local_exception_handling()
{
do
{
try
{
std::cout << "Input an integer (local exception handling, enter a text for exception): ";
std::string input;
std::cin >> input;
// stoi is a function that can throw exceptions
// look at the documentation https://en.cppreference.com/w/cpp/string/basic_string/stol
// and look for exceptions.
//
int value = std::stoi(input);
// if input was ok, no exception was thrown so we can return the value to the client.
return value;
}
// catch by const reference, it avoids copies of the exception
// and makes sure you cannot change the content
catch (const std::invalid_argument& e)
{
// std::exceptions always have a what function with readable info
std::cout << "handling std::invalid_argument, " << e.what() << "\n";
}
catch (const std::out_of_range& e)
{
std::cout << "handling std::out_of_range, " << e.what() << "\n";
}
} while (true);
}
int get_int_no_exception_handling()
{
std::cout << "Input an integer (without exception handling, enter a text for exception): ";
std::string input;
std::cin >> input;
int value = std::stoi(input);
return value;
}
int main()
{
try
{
// this function shows you can handle exceptions locally
// to keep program running
auto value1 = get_int_with_local_exception_handling();
std::cout << "your for input was : " << value1 << "\n";
// this function shows that exceptions can be thrown without
// catching, but then the end up on the next exception handler
// on the stack, which in this case is the one in main
auto value2 = get_int_no_exception_handling();
std::cout << "your input was : " << value1 << "\n";
return 0;
}
catch (const std::exception& e)
{
std::cout << "Unhandled exception caught, program terminating : " << e.what() << "\n";
return -1;
}
catch (...)
{
std::cout << "Unknown, and unhandled exception caught, program terminating\n";
}
}
uj5u.com熱心網友回復:
是和否。
不,因為通過拋出的任何例外throw some_exception;都可以通過catch(...).
是的,因為catch(...)不是很有用。你只知道有一個例外,但不知道更多。
通常,例外會攜帶有關您要在捕獲中使用的原因的資訊。僅作為最后的手段或當您需要確保不會錯過任何您應該使用的例外時catch(...):
try {
might_throw_unknown_exceptions();
} catch(std::exception& err) {
std::cout << "there was a runtime error: " << err.what();
} catch(...) {
std::cout << "an unknown excpetion was thrown.";
}
C 標準庫很少使用繼承。例外只是它被廣泛使用的地方:所有標準例外都繼承自,std::exception并且從它繼承自定義例外也是一種很好的做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325456.html
