목차
- Exceptions 정의
- try...catch... 구문
- finally 구문
- throw 키워드
Exceptions 정의
에러는 (의도적, 잘못 입력, 예측 불가 등) 여러 요인으로 생기는데,
C#은 프로그램 실행 중 에러 발생 시, 멈춘 후 에러 메세지를 생성.
즉, 정상적 실행의 예외적 경우 (= 오류)를 다루는 기술을 의미함.
try...catch... 구문
[구문]
try
{
// 테스트 할 실행 코드
}
catch(Exception e)
{
// 에러 발생 시 실행할 코드
}
PS. try...catch... 구문은 쌍으로 함께 사용.
[에러 발생 시, try...catch... 구문으로 처리 안 한 경우]
: C#의 기본 에러메세지가 그대로 노출됨.
[예제] Program.cs
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
int[] nums = {1, 2, 3};
Console.WriteLine(nums[5]); // 에러 발생.
}
}
}
결과값:
Unhandled Exception:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' ....
[에러 발생 시, try...catch... 기본 구문으로 처리한 경우]
파일명: Program.cs
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
try
{
int[] nums = {1, 2, 3};
Console.WriteLine(nums[5]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
결과값: Index was outside the bounds of the array.
[에러 발생 시, try...catch... 사용자 정의 구문으로 처리한 경우]
※ e.Message 대신, "뭔가 오류 발생." 사용자 정의 문구를 출력.
파일명: Program.cs
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
try
{
int[] nums = {1, 2, 3};
Console.WriteLine(nums[5]);
}
catch (Exception e)
{
Console.WriteLine("뭔가 오류 발생.");
}
}
}
}
결과값: 뭔가 오류 발생.
finally 구문
try...catch...구문 결과와 무관하게 그 이후에 실행할 코드 정의.
[예제] Program.cs
using System;
namespace Homzzang
{
class Program
{
static void Main(string[] args)
{
try
{
int[] nums = {1, 2, 3};
Console.WriteLine(nums[10]);
}
catch (Exception e)
{
Console.WriteLine("뭔가 오류 발생.");
}
finally
{
Console.WriteLine("'try catch' 구문 종료.");
}
}
}
}
결과값:
뭔가 오류 발생.
'try catch' 구문 종료.
throw 키워드
사용자 지정 오류 생성.
1.
exception 클래스와 함께 사용
2.
C#엔 다양한 exception 클래스 있음. (예)
ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, 기타 등등.
[에러 발생 O]
using System;
namespace Homzzang
{
class Program
{
static void checkLevel(int level)
{
if (level < 3)
{
throw new ArithmeticException("이용 불가.");
}
else
{
Console.WriteLine("이용 가능.");
}
}
static void Main(string[] args)
{
checkLevel(2);
}
}
}
결과값:
Unhandled Exception:
System.ArithmeticException: 이용 불가. ...
[에러 발생 X]
using System;
namespace Homzzang
{
class Program
{
static void checkLevel(int level)
{
if (level < 3)
{
throw new ArithmeticException("이용 불가.");
}
else
{
Console.WriteLine("이용 가능.");
}
}
static void Main(string[] args)
{
checkLevel(3);
}
}
}
결과값: 이용 가능.
최신댓글