The try { } catch (Exception e) { } finally { } structure is functionally identical to C++'s exception handling already documented in [[CPP Exceptions]], but where C++ typically catches by REFERENCE to a specific exception type (catch (std::exception& e)) and reads its message via .what(), C# catches the generic base Exception type and reads the message via a .Message PROPERTY (no parentheses — consistent with the property-not-method pattern already confirmed for .Length in the Strings chapter); throw new ArithmeticException("...") also demonstrates that C# ships a family of ready-made, semantically-named exception classes (ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException) rather than requiring the programmer to define custom exception types from scratch for common cases. [S1]
🧠 핵심 개념 (Core concepts)
Exception — the technical term for an error C# "throws" when something goes wrong (bad input, coding errors, unforeseen conditions). [S1]
try { } — a block of code tested for errors during execution. [S1]
catch (Exception e) { } — a block that runs IF an error occurs inside the paired try block; e is a variable holding the exception object. [S1]
e.Message — a property (no parentheses) on the caught exception, describing what went wrong. [S1]
finally { } — runs AFTER the try/catch, regardless of whether an error occurred or was caught. [S1]
throw new ExceptionType("message") — creates and raises a CUSTOM error, using one of C#'s built-in exception classes (ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc.). [S1]
📖 세부 내용 (Details)
Unhandled error: int[] myNumbers = {1, 2, 3}; Console.WriteLine(myNumbers[10]); → System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'. [S1]
Caught with built-in message: try { ...myNumbers[10]... } catch (Exception e) { Console.WriteLine(e.Message); } → "Index was outside the bounds of the array.". [S1]
Caught with custom message: catch (Exception e) { Console.WriteLine("Something went wrong."); } → "Something went wrong." (note: e is available but not necessarily used). [S1]
With finally: adding finally { Console.WriteLine("The 'try catch' is finished."); } runs that line AFTER the catch block regardless of outcome. [S1]
Custom throw: static void checkAge(int age) { if (age < 18) { throw new ArithmeticException("Access denied - You must be at least 18 years old."); } else { Console.WriteLine("Access granted - You are old enough!"); } } ... checkAge(15); → throws System.ArithmeticException: 'Access denied...'; checkAge(20); → prints "Access granted - You are old enough!". [S1]
⚖️ 모순 및 업데이트 (Contradictions & updates)
C++의 예외 처리와 구조는 동일, 메시지 접근 방식이 다름: try/catch/finally 구조 자체는 [[CPP Exceptions]]에서 확인된 C++와 차이가 없지만, C++가 보통 .what() 메서드로 예외 메시지를 얻는 반면 C#은 .Message라는 프로퍼티(괄호 없음)로 접근한다는 점이 확인됨 — Strings 챕터에서 확인된 프로퍼티 vs 메서드 구분이 예외 객체에도 그대로 적용됨. [S1]
즉시 사용 가능한 다양한 내장 예외 클래스 제공: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException 등 의미가 명확한 예외 클래스들이 기본 제공되어, throw할 때 매번 커스텀 예외 타입을 새로 정의할 필요가 없다는 점이 확인됨. [S1]
🛠️ 적용 사례 (Applied in summary)
나이가 18세 미만이면 ArithmeticException을 throw하고, 18세 이상이면 "Access granted"를 출력하는 checkAge() 함수 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
💻 코드 패턴 (Code patterns)
try/catch/finally with a custom throw (C#):
staticvoidcheckAge(intage){if(age<18){thrownewArithmeticException("Access denied - You must be at least 18 years old.");}else{Console.WriteLine("Access granted - You are old enough!");}}try{checkAge(15);}catch(Exceptione){Console.WriteLine(e.Message);// property, no parentheses}finally{Console.WriteLine("The 'try catch' is finished.");}
✅ 검증 상태 및 신뢰도
상태: draft
검증 단계: conceptual
출처 신뢰도: B (W3Schools — widely used educational reference, not a primary standards body)