>  기사  >  백엔드 개발  >  C#의 사용자 정의 예외

C#의 사용자 정의 예외

王林
王林원래의
2024-09-03 15:21:32987검색

우리가 작업 중인 애플리케이션에서는 비즈니스 규칙 위반이 발생하면 상황을 처리하기 위해 사용자 지정 예외를 발생시킵니다. 사용자 지정 예외는 애플리케이션의 고유한 시나리오를 해결하기 위해 특별히 생성된 예외입니다. 사용자 지정 예외를 만들려면 C#의 ApplicationException 또는 Exception 클래스에서 새 클래스를 파생시킵니다. ApplicationException 클래스는 .NET v1.0 버전부터 .NET Framework에 포함되어 있으며 C#에서 사용자 지정 예외 클래스의 기본 클래스 역할을 하도록 설계되었습니다.

C#에서 사용자 정의 예외 작업

  • 예외는 애플리케이션 실행 중에 발생하는 오류 유형을 처리합니다. 오류란 애플리케이션 실행 중에 발생하는 예상치 못한 문제를 의미합니다. 반대로, 여러 가지 이유로 애플리케이션 실행 중에 예외가 발생할 것으로 예상됩니다.
  • 예외 처리는 애플리케이션 실행 중에 발생할 것으로 예상되는 예외를 처리하기 위해 애플리케이션에서 사용됩니다. C#의 예외 처리는 try, catch, finally 및 throw라는 두 키워드를 사용하여 수행됩니다.
  • 클래스는 C#의 예외를 나타냅니다. C#의 이러한 예외 클래스는 System에서 파생됩니다. 직접적이든 간접적이든 예외 클래스입니다.
  • Application Exception 클래스 또는 Exception 클래스는 발생할 수 있는 사용자 정의 예외를 생성하는 데 사용됩니다.
  • 사용자 정의 예외 생성은 이러한 예외를 포착하고 다른 방식으로 처리할 수 있는 경우에만 유용합니다.
  • C#에서 Custom Exception을 생성하면 애플리케이션에서 발생한 오류와 오류 로그를 오류 모니터링 도구를 통해 모니터링할 수 있습니다.

다음은 언급된 예입니다.

예시 #1

프로그램에서 사용자 정의 예외 사용을 보여주는 C# 프로그램

코드:

using System;
//a namespace called user defined is defined
namespace UserDefined
{
//a class called test weather is defined
class Testweather
{
//main method is called
static void Main(string[] args)
{
//an instance of the class temperat is defined
Temperat tem = new Temperat();
try
{
//the show method of temperat class is called using the instance of the temperat class
tem.show();
}
catch(WeatheriscoldException e)
{
Console.WriteLine("The weather is cold Exception: {0}", e.Message);
}
Console.ReadKey();
}
}
}
//a custom exception class called Weather is cold Exception class is created which is thrown if the weather is cold
public class WeatheriscoldException: Exception
{
public WeatheriscoldException(string message): base(message)
{
}
}
//a class called temperat is defined
public class Temperat
{
//a variable called temp is defined and assigned to zero
int temp = 0;
//a method called show is defined
public void show()
{
//the temperature is checked to determine the weather
if(temp == 0)
{
throw (new WeatheriscoldException("The temperature is found to be zero and hence the weather is cold"));
}
else
{
Console.WriteLine("The Temperature is: {0}", temp);
}
}
}

출력:

C#의 사용자 정의 예외

설명:

  • 위 프로그램에는 user-define이라는 네임스페이스가 정의되어 있습니다. 그런 다음 test Weather라는 클래스가 정의됩니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 클래스 온도의 인스턴스가 정의됩니다. 그런 다음 온도 클래스의 인스턴스를 사용하여 온도 클래스의 표시 메소드를 호출합니다.
  • 그런 다음 날씨가 추우면 발생하는 Weather is cold 예외 클래스라는 사용자 정의 예외 클래스가 생성됩니다. 그런 다음 온도라는 클래스가 정의됩니다. 그런 다음 temp라는 변수가 정의되고 0에 할당됩니다. 그런 다음 show라는 메서드가 정의됩니다. 그런 다음 온도를 확인하여 날씨를 판단합니다.

예시 #2

프로그램에서 사용자 정의 예외 사용을 보여주는 C# 프로그램

코드:

using System;
//a namespace called exception handling is defined
namespace ExceptionHandling
{
//The custom exception class called odd num exception class is created by inheriting the exception class
public class OddNumException : Exception
{
//The property message is being overridden here
public override string Message
{
get
{
return "There cannot be an odd divisor";
}
}
}
//a class called check is defined
class check
{
//main method is called
static void Main(string[] args)
{
//three integer variables are defined
int a, b, c;
Console.WriteLine("Please enter two numbers and type of the numbers must be integer:");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
try
{
//checking if the divisor is an odd number or an even number
if (b % 2 > 0)
{
//exception is thrown if the divisor is an odd number
throw new OddNumException();
}
c = a / b;
Console.WriteLine(c);
}
catch (OddNumException two)
{
Console.WriteLine(two.Message);
}
Console.WriteLine("The program ends here");
Console.ReadKey();
}
}
}

출력:

C#의 사용자 정의 예외

설명:

  • 위 프로그램에는 예외 처리라는 네임스페이스가 정의되어 있습니다. 그런 다음 홀수 예외 클래스라고 하는 이 클래스는 예외 클래스를 상속하여 생성됩니다. 그런 다음 속성 메시지가 재정의됩니다. 그런 다음 check라는 클래스가 정의됩니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 3개의 정수 변수를 정의하여 2개의 입력 정수 변수를 취하고, 다른 정수 변수는 정수 출력을 저장하는 데 사용됩니다.
  • 그런 다음 두 정수 변수는parse() 메서드를 사용하여 구문 분석됩니다. 그런 다음 두 번째 정수 변수 또는 제수가 홀수인지 짝수인지 확인하고, 이는 제수를 2로 나눈 나머지가 0보다 크거나 0인지 확인하여 수행됩니다. 그런 다음 제수가 홀수이면 예외가 발생합니다.

장점

다음은 언급된 장점입니다.

  • C#에서 사용자 정의 예외 유형의 사용자 정의 처리는 코드를 호출하여 수행할 수 있습니다.
  • C#의 사용자 정의 예외 처리를 사용하여 사용자 정의 예외 유형에 대한 모니터링을 사용자 정의할 수 있습니다.

위 내용은 C#의 사용자 정의 예외의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.