728x90
반응형
예외가 발생할 수 있는 코드에 대한 대비
- 소스 코드를 작성하다 보면 다양한 예외(exception)를 만나는 경우가 많음
- C#에서는 이러한 예외를 효율적으로 쉽게 처리할 수 있는 코드를 제공함
- 이러한 예외 처리에 대한 예시로 중요한 파일 입출력이 있음
- 파일 입출력 중 예외가 발생한 상황에 대한 처리로 프로그램 안정성을 높일 수 있음
- 예외에 대한 처리를 통해 어떤 예외가 발생했는지 확인하고 디버깅할 수 있음
- 프로그램 동작의 안정성을 위한 예외 처리는 try-catch 구문을 사용하면 됨
- 또 추가로 디버깅을 위해 어떤 예외가 발생했는지 기록을 하면 됨
예시 소스코드
- 이 두 가지 사용법에 대한 예시 소스 코드는 아래와 같음
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
51
52
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionExampleInConsole
{
class Program
{
static void Main(string[] args)
{
// run func.
bool rst = _exFunc();
// check bool
if (rst)
{
Console.WriteLine("true");
}
return;
}
static bool _exFunc()
{
try
{
// normal : "file.txt"
// exception : "_file.txt"
string filePath = "_file.txt";
string[] readLines = System.IO.File.ReadAllLines(filePath);
string value = readLines[0];
if (value == "value")
{
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
Console.WriteLine(String.Format("[{0}] exception info. : {1}", DateTime.Now.ToString("HH:mm:ss.fff"), ex.ToString()));
return false;
}
}
}
}
|
cs |
소스코드에 대한 설명
- 위의 예시 코드에서 '_exFunc()'는 어떤 파일('file.txt')을 읽어 string을 비교 확인하는 코드임
- 'try{...}'에서 '...'에 동작시킬 코드를 입력하였음
- 'catch(Exception ex){...}'에서 '...'에 예외 발생 시에 동작시킬 코드를 입력하였음
- 도식으로 나타내면 아래와 같음
- 파일 이름이 'file.txt'인 경우 정상 동작하며 'true'라는 값을 콘솔 창에 출력 (break point 활용)
- 이 예시에서 파일 이름을 다른 것('_file.txt')으로 바꾸면 'System.IO.File.ReadAllLines'에서 파일을 찾을 수 없다는 예외가 발생
- 'catch(Exception ex){...}'에서 예외 발생 시 처리하는 코드가 있어 프로그램이 비정상 종료되지 않고 'Console.WriteLine'의 구문을 실행 (break point 활용)
- 예외를 'ex'라는 변수로 받아 'catch' 구문 내에서 활용할 수 있음
- 여기서는 이를 'Console.WriteLine'에서 출력하여 어떤 예외가 발생했는지 확인할 수 있게(logging) 코드가 작성되어 있음
- 이를 확인하여 어떤 문제가 있는지 확인하고 디버깅을 할 수 있음
Reference
- https://github.com/daegukdo/TIL/tree/master/02_C_sharp/024_ExceptionExampleInConsole
- https://stackoverflow.com/questions/3491213/logging-exception-in-c-sharp/3491230#3491230
logging exception in c#
logging exception the code below allows to save the content of an exception in a text file. Here I'm getting only the decription of the error. but it is not telling me where the exception occur...
stackoverflow.com
GitHub - daegukdo/TIL: today I learned
today I learned. Contribute to daegukdo/TIL development by creating an account on GitHub.
github.com
반응형
'Study > C#' 카테고리의 다른 글
파일의 무결성 확인 방법 (0) | 2022.05.05 |
---|---|
BackgroundWorker를 통해 조금 더 안전하게 이벤트 기반으로 비동기 처리를 진행하는 패턴 사용해보기 (RunWorkerAsync, IsBusy) (0) | 2021.10.13 |
nameof() 연산자의 활용 (0) | 2021.09.29 |
String.Format()을 보간 문자열로 대체하기 (0) | 2021.07.29 |
캐스트보다는 is, as가 더 좋음 (0) | 2021.07.28 |