免費開始練習
高考申論題 112年 [資訊處理] 程式設計

第 一 題

📖 題組:
二、關於以下C++程式碼:
01 #include <iostream>
02 #include <string>
03 #include <exception>
04 #include <stdexcept>
05 #include <assert.h>
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)<<endl; }
21 catch (std::exception &e) { cout << "1: " << e.what() << "\n"; }
22 }
23 void testResult() {
24 f(2, -1);
25 f(2, 0);
26 f(2, 3);
27 f(6, 3);
28 }
29 void assertResult() {
30 assert(getResult(8, 4)==1);
31 }
32 int main() {
33 testResult();
34 assertResult();
35 return 0;
36 }
📝 此題為申論題,共 2 小題

小題 (一)

請說明程式執行後的輸出。(15分)

思路引導 VIP

看到本題,首先要追蹤 main 函式中呼叫 testResult() 與 assertResult() 的過程。

  1. testResult 呼叫了四次 f() 函式,f() 內含 try-catch 結構來捕捉異常。
🤖
AI 詳解
AI 專屬家教

【考點分析】 本題主要考驗 C++ 中的例外處理機制(Exception Handling)、整數除法(Integer Division)、多型捕捉(Catching base class references)以及斷言(Assertion)的執行結果。 【分析與論述】

小題 (二)

請說明程式中assert與exception的使用時機與目的。(10分)

思路引導 VIP

這是一道觀念題。看到這題,要比較「斷言(Assertion)」與「例外(Exception)」在軟體工程與程式設計上的定位。

  1. Assert (斷言):主要用於「開發與除錯階段」,用來檢查程式的「內部不變性(Invariants)」或「不可能發生的邏輯錯誤」。一旦發生,代表程式有 Bug,應立即中斷。發布(Release)版本通常會關閉 assert。
🤖
AI 詳解
AI 專屬家教

【考點分析】 本題測驗軟體開發中錯誤處理(Error Handling)的兩種不同機制與設計哲學:斷言機制(Assertion)與例外處理(Exception Handling)的本質差異與應用情境。 【理論與論述】

📝 同份考卷的其他題目

查看 112年[資訊處理] 程式設計 全題