예제코드 for 문에서 배열 범위 밖의 요소 접근 시, 예외 메시지 출력하고 프로그램 종료
배열 객체는 예외에 대한 상세정보를 IndexOutofRangeException 객체에 담은 후 Main() 메소드에 던짐
Main() 메소드는 예외를 CLR에 던짐
CLR까지 전달된 예외는 “처리되지 않은 예외”가 되고, 예외 관련 메시지 출력 후 강제 종료
using System;
namespace Exception
{
class MainApp
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3 };
for (int i = 0; i < 5; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("종료"); // 실행 X
}
}
}
예외 처리 (Exception Handling)
예외가 프로그램의 오류 또는 다운으로 이어지지 않도록 적절하게 처리
기본 에러 처리와 고급 에러 처리로 나눌 수 있음
기본 예외 처리
예외가 발생하지 않게 사전에 해결
using System;
namespace Exception
{
class MainApp
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3 };
for (int i = 0; i < 5; i++)
{
// 기본 에러 처리
if (i < arr.Length) // 인덱스가 배열의 길이를 넘는지 사전에 확인
Console.WriteLine(arr[i]);
else
Console.WriteLine("인덱스 범위를 넘었습니다.");
}
Console.WriteLine("종료");
}
}
}
고급 에러 처리 : try ~ catch로 예외 받기
C#에서 예외를 받을 때 try ~ catch 문을 이용
이전 슬라이드 예제에서 배열이 IndexOutRangeException 예외를 던졌을 때, Main() 메소드는 try ~ catch 문으로 예외를 받을 수 있음
using System;
namespace ExceptionFiltering
{
class FilterableException : Exception
{
public int ErrorNo {get;set;}
}
class MainApp
{
static void Main(string[] args)
{
Console.WriteLine("Enter Number Between 0~10");
string input = Console.ReadLine();
try
{
int num = Int32.Parse(input);
if (num < 0 || num > 10)
throw new FilterableException() { ErrorNo = num };
else
Console.WriteLine($"Output : {num}");
}
catch (FilterableException e) when (e.ErrorNo < 0)
{
Console.WriteLine("Negative input is not allowed.");
}
catch(FilterableException e) when (e.ErrorNo > 10)
{
Console.WriteLine("Too big number is not allowed.");
}
}
}
}
댓글