평소에 에러가 날 것 같은 부분에 대해서 얼마나 신경써서 코딩을 하시나요?
모든 상황에 대해서 예외처리까지 다 끝난 뒤에 빌드 하시나요?
아니면 일단 해보고 어떻게 되는지 상황을 보시나요?
저 같은 경우는 case by case인 것 같습니다.
유니티에서 mobile이나 hololens app을 개발할 때는 빌드하고 배포하고 하는 과정이 워낙 오래 걸려서 최대한 꼼꼼하게 코드를 작성합니다.
window 기반의 응용프로그램 개발시에는 바로바로 실행해서 확인해 보는 것 같아요.
산술 오버플로우 같은 경우에 따로 예외가 발생하지 않기 때문에 놓치기 쉬운데요.
c#에는 다음과 같은 방법으로 예외를 발생시켜주거나 혹은 무시하는 방법이 있습니다.
일단 키워드의 msdn정의를 먼저 볼까요.
checked
산술 오버플로가 났을 경우 예외를 발생 시켜 준다. msdn에는 이렇게 정의 되어 있습니다.
unchecked
checked와 반대로 오버플로우 검사를 비활성화 합니다.
int가 표현할 수 있는 가장 큰 수는 2147483647 입니다.
2147483647 보다 큰 수를 int로 표현하려고 하면 바로 오버플로우가 나게 됩니다.
using System;
namespace CheckingForOverflow
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(int.MaxValue);
int temp = int.MaxValue;
Console.WriteLine(++temp);
}
}
}
실행하면 다음과 같은 결과가 나옵니다.
결과는 이렇게 나옵니다.
만약 오버플로가 나는 것이 개발자의 의도가 아니고 예외를 발생시키는 것이 목적이라면 checked를 사용할 수 있습니다.
콘솔에 프린트 하는 부분을 checked 키워드로 감싸줘 보겠습니다.
Console.WriteLine(checked(++temp));
결과는 다음과 같이 예외가 발생되게 됩니다.
static void Main(string[] args)
{
try
{
Console.WriteLine(int.MaxValue);
int temp = int.MaxValue;
Console.WriteLine(checked(++temp));
}
catch
{
Console.WriteLine("An exception occurred because of an overflow.");
}
}
try catch로 감싸게 되면 다음과 같은 결과가 나옵니다.
checked 부분을 unchecked로 바꾸면 어떻게 될까요?
try
{
Console.WriteLine(int.MaxValue);
int temp = int.MaxValue;
//Console.WriteLine(checked(++temp));
Console.WriteLine(unchecked(++temp));
}
catch
{
Console.WriteLine("An exception occurred because of an overflow.");
}
msdn에서 정의된 대로 예외가 발생하지 않고 오버플로우가 나게 됩니다.
github 링크
https://github.com/Helloezzi/dotnetcore_checked_unchecked
Helloezzi/dotnetcore_checked_unchecked
Contribute to Helloezzi/dotnetcore_checked_unchecked development by creating an account on GitHub.
github.com
'Programing > dotnet core' 카테고리의 다른 글
[dotnetcore] system.flag를 활용한 enum(열거형) 의 사용법 (0) | 2020.05.11 |
---|---|
지역변수 & 지역변수 추론 (var type) (0) | 2020.03.10 |
[dotnetcore] 프로그램의 메모리와 성능 모니터링 하는 법을 통해 알아보는 string vs StringBuilder의 차이점 (0) | 2020.03.03 |
dotnetcore : try catch finally vs using (0) | 2020.02.19 |
goto문을 활용한 switch문 (0) | 2020.02.18 |