구체적인 예외 처리
Coddy의 GDScript 개발자를 위한 C# 코스 레슨. 48개 중 28번째.
GDScript에는 예외나 try/catch가 없습니다. "bad".to_int()는 조용히 0을 반환하므로 먼저 is_valid_int()를 확인해야 하며, 64비트 정수는 오버플로가 발생하면 순환합니다. C#의 int.Parse는 예외를 발생시키며 FormatException과 OverflowException을 구분합니다. 처리할 수 있는 오류만 잡고, 관련 없는 프로그래밍 오류를 숨기지 마세요.
예외가 발생하면 제어 흐름은 일치하는 catch로 이동합니다. 모든 프로그래밍 오류를 무시하는 대신 처리할 수 있는 구체적인 오류만 잡으세요. 정수 나눗셈은 0을 향해 버림합니다. 파싱 오류와 산술 오류는 별개의 문제이므로 모든 실패를 잘못된 입력이라고 설명하지 마세요.
GDScript 참고
extends Node
func _ready():
var text := "bad"
if not text.is_valid_int():
print("invalid")Main 내부의 C# 문
try { int.Parse("bad"); } catch (FormatException) { Console.WriteLine("invalid"); }이 내용은 핵심만 다룬 교육용 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.
참고 출력:
invalidC# 출력:
invalid챌린지
쉬움Parse를 사용해 정수 한 줄을 파싱하세요. 정수를 2로 나눈 몫을 반환하고, 형식 오류가 발생하면 invalid를, 값이 int 범위를 벗어나면 overflow를 반환하세요. 구체적인 catch 절을 사용하세요.
잠금 해제된 C# 파일을 수정하세요. 표시된 잠금 상태의 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인하고 마지막에 줄바꿈 하나를 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
GDScript 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 번째 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러