'잡기'에 해당되는 글 1건

  1. 2021.12.10 C# Try-Catch and TryParse() - 에러 잡기
반응형

입력 문자열 형식 에러 잡는 방법 두 가지를 알아보자.

Try-Catch 구문을 사용하거나 TryParse()를 사용할 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CS
{
    using static System.Console;
 
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            string ageText;
 
            Write("Enter your age: ");
            ageText = ReadLine();
 
            // Try-Catch
            try
            {
                age = int.Parse(ageText);
                WriteLine($"You are {age * 12} months old.");
            }
            catch (FormatException exc)
            {
                WriteLine($"The age entered, {ageText}, is not valid: {exc.Message}");
            }
            catch (Exception exc)
            {
                WriteLine($"Unexpected error: {exc.Message}");
            }
            finally
            {
                WriteLine("Goodbye.");
            }
 
            // TryParse()
            if (int.TryParse(ageText, out age))
            {
                WriteLine($"You are {age * 12} months old.");
            } else
            {
                WriteLine($"The age entered, {ageText}, is not valid.");
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

실행하고 숫자를 입력하면 아무 문제없이 출력된다.

 

숫자가 아닌 문자가 입력되면 에러가 발생하고 잘 처리된다.

 

반응형
Posted by J-sean
: