Exception Types
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 24번째.
C#에서 예외는 해당 오류를 나타내는 바에 따라 다양한 유형으로 분류됩니다. 이러한 유형을 이해하면 오류를 더 효과적으로 처리할 수 있습니다.
일반적인 예외 유형을 살펴보겠습니다:
모든 예외의 기본 클래스는 System.Exception입니다.
try
{
// 예외를 발생시킬 수 있는 코드
}
catch (Exception ex)
{
// 모든 예외 처리
Console.WriteLine(ex.Message);
}일반적인 예외 유형:
ArgumentException: 메서드가 잘못된 인수로 호출될 때 발생합니다.
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: null 참조의 멤버에 접근하려고 할 때 발생합니다.
string text = null;
// This will throw NullReferenceException
int length = text.Length;IndexOutOfRangeException: 배열 인덱스가 배열의 경계를 벗어났을 때 throw됩니다.
int[] numbers = { 1, 2, 3 };
// This will throw IndexOutOfRangeException
int value = numbers[5];DivideByZeroException: 정수를 0으로 나눌 때 발생합니다.
int result = 10 / 0; // This will throw DivideByZeroException특정 예외를 잡을 수 있습니다:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}챌린지
쉬움ProcessArray이라는 이름의 메서드를 생성하세요. 이 메서드는:
- 정수 배열과 인덱스를 매개변수로 받습니다
- 지정된 인덱스의 요소에 접근을 시도합니다
- 성공하면 요소 값을 반환합니다
IndexOutOfRangeException이 발생하면 이를 catch하고 -1을 반환합니다
메서드는 이 시그니처를 가져야 합니다:
public static int ProcessArray(int[] array, int index)치트 시트
모든 예외의 기본 클래스는 System.Exception입니다:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}일반적인 예외 유형:
ArgumentException: 메서드가 잘못된 인수로 호출될 때 발생합니다:
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: null 참조의 멤버에 액세스할 때 발생합니다:
string text = null;
int length = text.Length; // Throws NullReferenceExceptionIndexOutOfRangeException: 배열 인덱스가 범위를 벗어날 때 발생합니다:
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Throws IndexOutOfRangeExceptionDivideByZeroException: 정수를 0으로 나눌 때 발생합니다:
int result = 10 / 0; // Throws DivideByZeroException특정 예외 catch하기:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}직접 해보기
using System;
class Program
{
public static int ProcessArray(int[] array, int index)
{
// 여기에 코드를 작성하세요
return 0;
}
static void Main(string[] args)
{
// 배열 입력 읽기
string input = Console.ReadLine();
// 대괄호가 있으면 제거
if (input.StartsWith("[") && input.EndsWith("]"))
{
input = input.Substring(1, input.Length - 2);
}
string[] parts = input.Split(',');
int[] array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = int.Parse(parts[i].Trim());
}
// 인덱스 입력 읽기
int index = int.Parse(Console.ReadLine());
int result = ProcessArray(array, index);
Console.WriteLine(result);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety