์์ธ ์ฒ๋ฆฌ ๊ตฌ๋ฌธ(try
- catch
)
try{
// ์คํ์ฝ๋
}
catch(Exception ๊ฐ์ฒด1){
// ์ด๋ค ์์ธ๊ฐ ๋ฐ์ํ์๋ ์ฒ๋ฆฌ ์ฝ๋
}
catch(Exception ๊ฐ์ฒด2){
// catch๋ฌธ์ ์ฌ๋ฌ๊ฐ๊ฐ ์ฌ ์ ์๋ค.
}
...
Ex - ๊ธฐ์กด ์์ธ ๋ฐ์ ์ฝ๋
namespace ExceptionEx
{
class Program
{
static void Main(string[] args)
{
int[] array = {1,2,3,4,5};
for(int i = 0; i < 6; i++)
{
Console.WriteLine(array[i]);
}
Console.WriteLine("ํ๋ก๊ทธ๋จ ์ข
๋ฃ!!");
}
}
}
Output
1
2
3
4
5
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ExceptionEx.Program.Main(String[] args) in C:\Users\shkim\source\repos\ClassEx\practice1\Program.cs:line 31
์์ธ ๋ฐ์์ ์คํํ๋ ํ๋ก๊ทธ๋จ์ด ์์ธ๋ฅผ ์ถ๋ ฅํ๋ฉฐ ์ค์ง๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
์ด๋ try - catch ๊ตฌ๋ฌธ์ ์ฌ์ฉํ์ฌ ์์ธ๋ฅผ ์ฒ๋ฆฌํด์ฃผ๋ฉด ํ๋ก๊ทธ๋จ์ด ์ค์งํ์ง ์๋๋ค.
Ex - Use try-catch
using System.Collections;
namespace ExceptionEx
{
class Program
{
static void Main(string[] args)
{
try
{
int[] array = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 6; i++)
{
Console.WriteLine(array[i]);
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. : {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. : {e.Message}");
}
Console.WriteLine("ํ๋ก๊ทธ๋จ ์ข
๋ฃ!!");
}
}
}
Output
1
2
3
4
5
์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. : Index was outside the bounds of the array.
ํ๋ก๊ทธ๋จ ์ข
๋ฃ!!
- ํ๋ก๊ทธ๋จ ์ข ๋ฃ๋ฉ์ธ์ง๊ฐ ๋์ด. => ์ค๋ฅ๋ ์ก๊ณ ํ๋ก๊ทธ๋จ์ด ์ค์ง๊ฐ ๋๋ ํ์์ด ๋ฐ์ํ์ง ์์. ๋ง์ง๋ง๊น์ง ์ ์์ ์ผ๋ก ์ํ๋จ.
'๐ป Programming Language > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
29. System.Exceptionํด๋์ค, throw๋ฌธ (0) | 2022.04.07 |
---|---|
29-1. Null ๋ณํฉ ์ฐ์ฐ์(Null Operator) (0) | 2022.04.07 |
27. ์ ๋ค๋ฆญ ์ปฌ๋ ์ (0) | 2022.04.07 |
26. ์ ๋ค๋ฆญ์ค(Generics) ํ์ ์ ์ฝ (0) | 2022.04.07 |
25. ์ ๋ค๋ฆญ์ค(Generics) (0) | 2022.04.07 |