* 예외처리
* exception 사용
int[] a = { 1 };
try
{
for (int i = 0; i < 3; i++)
{
Console.Write(a[i]);
}
}
catch (Exception e)
{
Console.Write(e.Message);
}
// 배열값은 1개인데 3개까지 접근하게 되면 try는 catch에 데이터를 넘겨줌
// catch는 에러와 관련된 메세지를 출력함
* 예외 던지기
static void method(int a)
{
if (a > 10)
{
throw new Exception("abc");
}
}
static void Main(string[] args)
{
try {
method(1);
method(11);
}
catch(Exception e)
{
Console.Write(e.Message);
}
}
// 함수 부분에서 throw를 통해 에러 메세지 내용을 던졌다.
// 그냥 빈칸인 ()를 던져도 되지만 메세지를 입력하면 그 내용이 출력된다.
* finally
static void method(int a)
{
if (a > 10)
{
throw new Exception();
}
}
static void Main(string[] args)
{
try {
method(11); // 예외에 걸리지 않는 수로 변경 가능
}
catch(Exception e)
{
Console.WriteLine(e.Message); // 에러 내용이고 위치를 알고 싶으면 .stacktrace 사용
}
finally
{
Console.WriteLine("finally");
}
// 예외가 있든 없든 finally 부분은 출력을 한다.