개발/기본) 기본기
기본기) Custom Exception (사용자 정의 예외)
테샤르
2022. 7. 4. 10:59
Custom Exception (사용자 정의 예외)
Exception을 Custom 해서 사용자가 예외에 대해서 정의 가능하다.
반응형
생성방법은 다음과 같다.
[Serializable]
public class StudentNotFoundException : Exception
{
public string StudentName { get; }
public StudentNotFoundException() { }
public StudentNotFoundException(string message)
: base(message) { }
public StudentNotFoundException(string message, Exception inner)
: base(message, inner) { }
public StudentNotFoundException(string message, string studentName)
: this(message)
{
StudentName = studentName;
}
}
생성된 Custom Exception을 호출하는 방법은 다음과 같다.
try
{
if(failed Condition)
throw new StudentNotFoundException("The student cannot be found.", "John");
}
catch(AggregateException ae)
{
}
Custom Exception은 특정 상황에 대한 예외처리를 하기 위한 방법이다.
단순하게 State를 변경하는것으로도 개발할수있지만 명확하게 예외상황을 구분해주는 Custom Exception Class를 고려해보는것도 좋은 방법이라고 생각한다.
Microsoft .Net Create user -define Exeption : [링크]
★☆☆☆☆
반응형