예외가 발생하면 어떤 예외가 발생했는지와 관련된 정보를 전달해주면 편리합니다. 이러한 기능을 수행하게 하는 것이 예외 객체입니다.
예외 객체는 다음과 같이 catch 구문의 괄호 안에 들어있는 변수를 나타냅니다.
try
{
}
catch(Exception exception) // Exception 클래스의 인스턴스로 예외 객체라고 부릅니다.
{
}
예외 객체의 속성과 메서드를 몇 가지 사용해서 예외와 관련된 정보를 출력해봅니다.
static void Main(string[] args)
{
Console.Write("입력 : " );
string input = Console.ReadLine();
try
{
int index = int.Parse(input);
Console.WriteLine("입력 숫자 : " + index);
}
catch(Exception exception)
{
Console.WriteLine("예외가 발생했습니다.");
Console.WriteLine(exception.GetType());
Console.WriteLine(exception.Message);
Console.WriteLine(exception.StackTrace);
}
}
/*
[실행 결과]
입력 : ㅇㅅㅇ
예외가 발생했습니다.
System.FormatException
입력 문자열의 형식이 잘못되었습니다.
위치 : System.Number.StringToNumber(String str, ... 생략 ...
*/
여기까지는 예외가 발생했을 경우 이를 어떻게 처리하는지 알아보았습니다.
그렇다면 예외를 강제로 발생시킬 수는 없을까요?
예외를 강제로 발생시키기 위해서는 throw 키워드를 사용하면 됩니다.
throw new Exception();
강제로 던진 예외를 처리하는 코드를 만들어보겠습니다.
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
catch(Exception exception)
{
Console.WriteLine("예외 발생");
}
}
}
/*
[실행 결과]
예외 발생
*/
위는 간단한 코드이고 조금 더 실용적인 예제를 보도록 하겠습니다.
Box 의 너비와 높이를 받는 프로그램에 음수를 입력했을 떄 오류 메세지를 출력하는 예제를 만들어보겠습니다.
class Program
{
class Box
{
// 변수와 속성
private int width;
public int Width
{
get { return width; }
set
{
if( value > 0 ) { width = value; }
else { throw new Exception("너비는 자연수를 입력해주세요");
}
}
private int height;
public int Height
{
get { return height; }
set
{
if( value > 0 ) { height = value; }
else { throw new Exception("높이는 자연수를 입력해주세요");
}
}
public Box(int width, int height)
{
Width = width;
Height = height;
}
public int Area() { return this.width * this.height; }
}
static void Main(string[] args)
{
Box box = new Box(-10, -20);
}
}
/*
[실행 결과]
처리되지 않은 예외 : System.Exception : 너비는 자연수를 입력해주세요
*/
'C# > 프로그래밍 고급' 카테고리의 다른 글
C# 프로그래밍 고급 - 07. 람다식 (0) | 2024.05.30 |
---|---|
C# 프로그래밍 고급 - 06. 델리게이터 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 04. 예외처리 (0) | 2024.05.29 |
C# 프로그래밍 고급 - 03. 인터페이스 멤버와 다중 상속 (0) | 2024.05.29 |
C# 프로그래밍 고급 - 02. 인터페이스 생성 (0) | 2024.05.29 |