- System.Exception ํด๋์ค๋ ๋ชจ๋ Exception์ Baseํด๋์ค์ด๋ค.
- ๋ชจ๋ Exception๋ค์ System.Exception ํด๋์ค๋ฅผ ์์๋ฐ๋๋ค.
- ์์ ์ฌ์ฉํ๋ IndexOutOfRangeException ์์ธ ํด๋์ค๋ System.Exception์ผ๋ก๋ถํฐ ํ์๋ ๊ฒ
- System.Exception์ ์ด์ฉํด์ ๋ชจ๋ ์์ธ์ฌํญ์ ์ฒ๋ฆฌํ์ง ์๋ ์ด์
- ๊ฐ๋ฐ์๊ฐ ์์ํ์ง ๋ชปํ๋ ์์ธ๋ฅผ ์ฒ๋ฆฌํ ์๋ ์์ง๋ง, ์ฒ๋ฆฌํ์ง ์์๋ ๋ ์์ธ๊น์ง ๋ชจ๋ ์ฒ๋ฆฌ๋ฅผ ํจ์ผ๋ก์จ ์ค๋ฅ๊ฐ ๋ฐ์ํ ์ ์๊ธฐ ๋๋ฌธ์ System.Exception์ ์ฌ์ฉํ๋ ๊ฒ์ ์ ์คํ๊ฒ ๊ณ ๋ คํด์ผํ๋ค.
throw๋ฌธ ํ์
try
{
throw new Exception("์์ธ๋ฅผ ๋์ง");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
์ฌ์ฉ ์ฝ๋ ์์
using System.Collections;
namespace ExceptionEx
{
class Program
{
static void throwMethod(int aa)
{
if (aa < 5 ) { Console.WriteLine($"{aa}"); }
else { throw new Exception("aa๋ 5๋ณด๋ค ํฌ๋ค."); }
}
static void Main(string[] args)
{
try
{
throwMethod(1);
throwMethod(2);
throwMethod(3);
throwMethod(4);
throwMethod(5); // => catch ๋ฌธ์ผ๋ก ๋์ด๊ฐ
throwMethod(6); // 6์ ์ํ๋์ง ์์.
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("์ข
๋ฃ");
}
}
}
Output
1
2
3
4
aa๋ 5๋ณด๋ค ํฌ๋ค.
์ข
๋ฃ
- try๋ฌธ ๋ด์์ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด try๋ฌธ ๋ด ์ฝ๋๋ฅผ ๋ชจ๋ ์คํํ์ง ์๊ณ catch๋ฌธ์ผ๋ก ์์ธ๋ฅผ ๋์ง๋ฉฐ ๋์ด๊ฐ๋ค.
- ์ดํ catch๋ฌธ ๋ด ์ฝ๋๋ฅผ ์คํํ ๋ค catch๋ฌธ์ ๋ฒ์ด๋ ๋ค๋ฅธ ์ฝ๋๋ฅผ ์คํํ๊ณ ํ๋ก๊ทธ๋จ์ ์ ์ ์ข
๋ฃํ๋ค.
- ์ฆ, try๋ฌธ ๋ด์์ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด ํด๋น try๋ฌธ ๋ด์์์ ๋์์ ์ค์งํ์ง๋ง ํ๋ก๊ทธ๋จ์ ์ ์ฒด์ ์ธ ๋์์ ์ ์์ ์ผ๋ก ๋์ํ๋ค.