๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ/C#

[C#] try catch์™€ throw๋ฌธ/์‹

by HanaV 2023. 8. 25.
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

"); wcs_do();