개발언어/C#
[C#] throw를 써서 try~catch로 예외던지기
창용이랑
2023. 5. 19. 11:19
728x90
try~catch로 예외를 처리할 때 예외를 받는데
어디선가 예외를 던진다는 얘기도 됩니다.
예외는 throw 문을 이용해서 던집니다.
try
{
//
throw new Exception("예외를 던집니다.");
}
catch(Exception e) // throw 문을 통해서 던져진 예외 객체는 catch 문으로 받습니다.
{
Console.WriteLine(e.Message);
}
특정 조건을 만족하지 않으면 예외를 던지고 try~catch 문에서 받습니다.
static void DoSomething(int age)
{
if(age<10)
Console.WriteLine("age: {0}", age);
else
// DoSomething() 안에서 예외 처리 코드가 없기 때문에 DoSomething() 호출자에게 던집니다.
throw new Exception("age가 10보다 큽니다.");
}
static void Main()
{
try
{
DoSomething(13); // 던져진 예외가 있다면 catch 블록에서 받습니다.
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
throw 예제
using System;
namespace Throw
{
class Program
{
static void DoSomething(int age)
{
if (age < 10)
Console.WriteLine("age: {0}", age);
else
throw new Exception("age가 10보다 큽니다.");
}
static void Main(string[] args)
{
try
{
DoSomething(1);
DoSomething(3);
DoSomething(5);
DoSomething(9);
DoSomething(11);
DoSomething(13);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}