高考申論題
112年
[資訊處理] 程式設計
第 二 題
📖 題組:
二、關於以下C++程式碼: 01 #include
02 #include
03 #include
04 #include
05 #include
06 using namespace std;
07 class NegativeException: public exception {
08 const char * what () const throw () { return "negative"; }
09 };
10 class DivideByZeroException: public logic_error{
11 public:
12 DivideByZeroException() : logic_error( "divide by zero" ) {}
13 };
14 int getResult(int x, int y) {
15 if (x<0 || y<0) throw NegativeException();
16 else if (y==0) throw DivideByZeroException();
17 return (x/y);
18 }
19 void f(int x, int y) {
20 try { cout << "Result:"<< getResult(x, y)<
二、關於以下C++程式碼: 01 #include
📝 此題為申論題,共 2 小題
小題 (二)
請說明程式中assert與exception的使用時機與目的。(10分)
思路引導 VIP
這是一道觀念題。看到這題,要比較「斷言(Assertion)」與「例外(Exception)」在軟體工程與程式設計上的定位。
- Assert (斷言):主要用於「開發與除錯階段」,用來檢查程式的「內部不變性(Invariants)」或「不可能發生的邏輯錯誤」。一旦發生,代表程式有 Bug,應立即中斷。發布(Release)版本通常會關閉 assert。
小題 (一)
請說明程式執行後的輸出。(15分)
思路引導 VIP
看到本題,首先要追蹤 main 函式中呼叫 testResult() 與 assertResult() 的過程。
testResult呼叫了四次f()函式,f()內含try-catch結構來捕捉異常。