728x90
try~catch
try catch๋ ์๋์ ๊ฐ์ด ์์ธ์ฒ๋ฆฌ์ ์ฐ์ธ๋ค.
try
{
// ์์ธ๊ฐ ๋ฐ์ํ ์ ์๋ ์ฝ๋
}
catch (์์ธ์ข
๋ฅ e) //๊ทธ ์์ธ๋ฅผ e๋ผ๋ ๋งค๊ฐ๋ณ์๋ก ๋ฐ์
{
// ์์ธ ์ฒ๋ฆฌ ์ฝ๋
}
catch (์์ธ์ข
๋ฅ ex) //๊ทธ ์์ธ๋ฅผ ex๋ผ๋ ๋งค๊ฐ๋ณ์์ ๋ฐ์
{
// ์์์ ์ฒ๋ฆฌํ์ง ์์ ๋ค๋ฅธ ์์ธ๋ค์ ์ฒ๋ฆฌํ๋ ๋ถ๋ถ
}
finally
{
// ์์ธ ๋ฐ์ ์ฌ๋ถ์ ์๊ด์์ด ํญ์ ์คํ๋๋ ์ฝ๋
}
throw
throw๋ ์์ธ๋ฅผ ๋์ง ๋ ์ฌ์ฉํ๋ค.
using System;
class Program
{
static void Main(string[] args)
{
try
{
int age = -1;
if (age < 0)
{
throw new ArgumentException("๋์ด๋ ์์์ผ ์ ์์ต๋๋ค.");
}
}
catch (ArgumentException e)
{
Console.WriteLine("์์ธ ๋ฐ์: " + e.Message);
}
}
}
throw๋ ๋ณดํต ๋ฌธ์ผ๋ก ์ฌ์ฉ๋๋, ์๋ ์์์ฒ๋ผ ์์ผ๋ก ์ฌ์ฉ๋ ์๋ ์๋ค.
string message = (age >= 0) ? "๋์ด๊ฐ ์ ํจํฉ๋๋ค." : throw new ArgumentException("๋์ด๋ ์์์ผ ์ ์์ต๋๋ค.");
int?a = null;
int b = a ?? throw new ArgumentNullException();
์ฌ์ฉ์ ์ ์ ์์ธ ํด๋์ค
์์ธ๋ฅผ ์ปค์คํ ํ ์๋ ์๋ค .
using System;
class CustomException : Exception
{
public CustomException(string message) : base(message)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
int age = -5;
if (age < 0)
{
throw new CustomException("๋์ด๋ ์์์ผ ์ ์์ต๋๋ค.");
}
Console.WriteLine("๋์ด: " + age); // ์ด ๋ถ๋ถ์ ์คํ๋์ง ์์
}
catch (CustomException ex)
{
Console.WriteLine("์ฌ์ฉ์ ์ ์ ์์ธ ๋ฐ์: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("์์ธ ๋ฐ์: " + ex.Message);
}
}
}
728x90
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C#] ๋๋ฆฌ์(delegate)์ ์ด๋ฒคํธ (0) | 2023.09.10 |
---|---|
[์ด๊ฒ์ด C#์ด๋ค] Chapter12: ์ฐ์ต๋ฌธ์ (0) | 2023.08.25 |
[์ด๊ฒ์ด C#์ด๋ค] Chapter11: ์ฐ์ต๋ฌธ์ (0) | 2023.08.22 |
[C#] ์ผ๋ฐํ ํ๋ก๊ทธ๋๋ฐ: ์ปฌ๋ ์ (0) | 2023.08.22 |
[C#] ์ผ๋ฐํ ํ๋ก๊ทธ๋๋ฐ: ๋ฉ์๋, ํด๋์ค, ์ ์ฝ์กฐ๊ฑด (0) | 2023.08.22 |