try{} catch{} finally{} 구성
--- 검사 연산, 메서드 ---
is 연산자: 변수의 타입을 확인합니다.
as 연산자: 타입 변환을 시도하고 실패하면 null을 반환합니다.
typeof 연산자: 변수의 타입 정보를 얻습니다.
GetType() 메서드: 실행 시간에 객체의 Type을 얻습니다.
null 검사: 변수가 null인지 확인합니다.
파이썬에서는 하단과 같은 에러 처리가 가능하다.
O : python 은 동적 타입 언어이므로 a = qwesa 같은 에러가 컴파일 에러가 아닌 런타임 에러기 때문에 try except 나 try catch 같은 예외 처리가 가능하다.
try:
a = qwesa
except Exception as e:
print(1111111111111111)
X : 하지만 C#은 정적 타입 언어이므로 a = qwesa 같은 에러는 컴파일단계에서 에러가 나므로 try except 나 try catch 로 예외처리가 불가능 하다.
try
{
var a = "qwesa"; // 'qwesa'를 문자열 리터럴로 정의합니다.
}
catch (Exception e)
{
Console.WriteLine(1111111111111111L);
}
python 에서 "raise TypeError("에러명 기입")"
C# 에서는 "throw new ArgumentException("에러명 기입");"
finally 구문
python
def SafeDivision():
raise TypeError()
print(1)
try:
print(" TRY ")
SafeDivision()
print( ---- PASS ------")
except Exception as e:
print(" CATCH ")
finally:
print(" FINALLY ")
print(2)
C#
namespace practice;
using System;
public class Program
{
static double SafeDivision()
{
throw new DivideByZeroException();
}
public static void Main()
{
Console.WriteLine("1");
try
{
Console.WriteLine(" TRY ");
SafeDivision();
Console.WriteLine($" ---- PASS ------"); // Output X
}
catch (DivideByZeroException)
{
Console.WriteLine(" CATCH ");
}
finally
{
Console.WriteLine(" FINALLY ");
}
Console.WriteLine("2");
}
}
is 연산자
object myObj = "Hello World";
if (myObj is string) {
// myObj가 string 타입인 경우 여기의 코드가 실행됩니다.
}
-- 타입 검사와 해당 타입으로의 변수 할당을 동시에 수행
val 가 int 면 j에 val 의 값을 넣는다.
object val = 42;
if (val is int j)
{
// 여기서 j는 val의 값을 가진 int 타입의 변수입니다.
Console.WriteLine(j); // 42를 출력합니다.
}
as 연산자
타입 변환을 시도하고, 변환이 불가능하면 null을 반환
public class Program
{
public static void Main()
{
object myObj = "Hello World"; // Hello World 출력됨
// object myObj = 123; // Fail 출력됨
if ( ( myObj as string ) is string a){
Console.WriteLine(a);
}else{
Console.WriteLine("Fail");
}
}
}
typeof 연산자
typeof(자료형) 이기 때문에 제네릭 T의 자료형을 확인하는 용도로 쓰이거나
타겟 type 이 해당 type 인지 비교 할때 사용된다.
static void F<T>(T x) => Console.WriteLine($"F<T>(T), T is {typeof(T)}");
GetType() 메서드
public class Program
{
public static void Main()
{
// object myObj = "Hello World";
object myObj = 123;
Type type = myObj.GetType();
if (type == typeof(string)) {
Console.WriteLine($"myObj 은 string type 이 맞습니다.");
}else{
Console.WriteLine($"myObj 은 string type 이 아닌 {type} 타입입니다.");
}
}
}
null 검사
public class Program
{
public static void Main()
{
string? myStr = null; // myStr 이 string 일 수도 null 일 수도 있는 자료형
// if (myStr == null) { // 두가지 방법 다 가능
if (myStr is null) {
Console.WriteLine("11111");
}
}
}
'언어 정리 > C# 개념 및 lib' 카테고리의 다른 글
예외처리 (0) | 2024.01.24 |
---|---|
익명 형식 vs 딕셔너리, 가변인자 (0) | 2024.01.24 |
제네릭 클래스, Nullable(?), IEnumerator(이터레이터) (1) | 2024.01.23 |
vscode with c# in wsl (1) | 2024.01.23 |
참조자, static method, 오버라이딩, 오버로드 (1) | 2024.01.09 |
댓글