이 글에서는 C# 개발 과정에서 발생할 수 있는 FormatException 에러에 대해 설명하고, 실무 코드 예제를 통해 원인 분석 및 해결 방법을 제시합니다.
문제상황
(에러가 발생한 코드)
using System;
namespace FormatExceptionExample
{
class Program
{
static void Main(string[] args)
{
string userInput = "1234.56";
int convertedNumber = int.Parse(userInput);
Console.WriteLine("Converted number: " + convertedNumber);
}
}
}
위 코드에서는 사용자로부터 입력받은 문자열을 정수로 변환하려고 시도합니다. 이때, 문자열이 "1234.56"처럼 소수점을 포함한 실수 형식이라면, int.Parse() 메서드가 예외를 발생시키게 됩니다.
에러로그 내용:
System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s)
at FormatExceptionExample.Program.Main(String[] args) in Program.cs:line 10
원인분석
FormatException은 일반적으로 문자열을 다른 형식의 값으로 변환하려고 할 때 입력 문자열이 대상 형식에 맞지 않는 경우에 발생합니다. 이 경우에는 문자열 "1234.56"을 정수로 변환하려고 시도했기 때문에 FormatException이 발생한 것입니다.
- 사용자로부터 "1234.56"과 같은 실수 형식의 문자열을 입력받습니다.
- int.Parse() 메서드를 사용하여 문자열을 정수로 변환하려고 시도합니다.
- "1234.56" 문자열은 정수 형식이 아니므로 int.Parse() 메서드는 FormatException 예외를 발생시킵니다.
해결방법-Int32.TryParse
에러가 수정된 코드+ 수정된 부분에 대한 주석
using System;
namespace FormatExceptionExample
{
class Program
{
static void Main(string[] args)
{
string userInput = "1234.56";
int convertedNumber;
// TryParse 메서드를 사용하여 문자열을 정수로 변환 시도
bool isSuccess = int.TryParse(userInput, out convertedNumber);
if (isSuccess)
{
Console.WriteLine("Converted number: " + convertedNumber);
}
else
{
Console.WriteLine("Invalid format for an integer.");
}
}
}
}
- 사용자로부터 "1234.56"과 같은 실수 형식의 문자열을 입력받습니다.
- int.TryParse() 메서드를 사용하여 문자열을 정수로 변환하려고 시도합니다. 이 메서드는 변환에 성공하면 true를 반환하고, 실패하면 false를 반환합니다.
- 문자열이 정수 형식이 아니므로 int.TryParse() 메서드는 false를 반환하고, out 파라미터를 통해 convertedNumber 변수에 할당되는 값은 0이 됩니다.
- 반환된 결과를 확인하여 성공적으로 변환되었는지 확인하고, 결과에 따라 적절한 메시지를 출력합니다.
해결방법-소수점을 고려한 변환
using System;
namespace FormatExceptionExample
{
class Program
{
static void Main(string[] args)
{
string userInput = "1234.56";
decimal convertedDecimal = decimal.Parse(userInput);
// 소수점 이하를 버리고 정수 부분만 취합니다.
int convertedNumber = (int)convertedDecimal;
Console.WriteLine("Converted number: " + convertedNumber);
}
}
}
- 사용자로부터 "1234.56"과 같은 실수 형식의 문자열을 입력받습니다.
- decimal.Parse() 메서드를 사용하여 문자열을 decimal 형식으로 변환합니다.
- 변환된 decimal 값을 int로 캐스팅하여 소수점 이하를 버리고 정수 부분만 취합니다.
- 변환된 정수 값을 출력합니다.
참고링크
728x90