>  기사  >  백엔드 개발  >  C#의 예외 유형

C#의 예외 유형

PHPz
PHPz원래의
2024-09-03 15:20:36811검색

프로그램 실행 중에 발생하는 문제는 예외이며 이러한 예외는 0으로 나누려고 할 때 발생하는 예외와 제어가 전송될 때 발생하는 예외와 같이 프로그램 실행 중에 예외적인 상황에 대한 응답입니다. 예외를 통해 프로그램의 한 부분에서 프로그램의 다른 부분으로 예외 처리는 C#의 4가지 키워드, 즉 try, catch, finally 및 throw 블록으로 관리됩니다.

C#의 예외 유형과 예제

C#에는 여러 유형의 예외가 있습니다. 그들은:

1. System.OutOfMemoryException

사용 가능한 메모리가 부족하여 발생하는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. OutOfMemoryException.

예:

//a class called check is defined
public class check
{
//main method is called
public static void Main()
{
// a string variable is created and tried to store 2.1 billion characters and this causes an out of memory exception
string val = new string('r', int.MaxValue);
}
}

출력:

C#의 예외 유형

출력:

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 문자열 변수가 생성되어 21억 개의 문자를 저장하려고 하면 메모리 부족 예외가 발생합니다.

2. System.NullReferenceException

Null 객체를 참조하여 생성된 오류는 이 예외에 의해 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. NullReferenceException

:

using System;
//a class called check is defined
class check
{
//main method is called
static void Main()
{
//a string variable is defined, and it is referencing to null
string value = null;
//the length of the value referencing to null is checked if it is equal to zero causing an exception
if (value.Length == 0)
{
Console.WriteLine(value);
}
}
}

출력:

C#의 예외 유형

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 문자열 변수가 정의되고 null을 참조합니다. 그런 다음 null을 참조하는 값의 길이가 0인지 확인하여 예외를 발생시킵니다.

3. System.InvalidCastException

타입 캐스팅 중에 생성되는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. InvalidCastException.

예:

using System.IO;
using System.Text;
//a class called check is defined
class check
{
//main method is called
static void Main()
{
// an instance of the string builder class is created which is then assigned to a new object through implicit casting and then casting is tried explicitly to convert the instance of stringbuilder class to streamreader class
StringBuilder ref1 = new StringBuilder();
object ref2 = ref1;
StreamReader ref3 = (StreamReader)ref2;
}
}

출력:

C#의 예외 유형

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 암시적 캐스팅을 통해 새 개체에 할당된 문자열 빌더 클래스의 인스턴스가 생성된 다음 명시적으로 캐스팅을 시도하여 stringbuilder 클래스의 인스턴스를 스트림리더 클래스로 변환하여 예외를 발생시킵니다.

4. System.ArrayTypeMismatchException

배열 유형과 유형이 일치하지 않을 때 발생하는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. ArrayTypeMismatchException.

예:

//a class called check is defined
class check
{
//main method is called
static void Main()
{
// a string is defined and assigned the values which is then assigned to object class array and then an integer is tried to put in the same array which causes an exception
string[] arr1 = { "Welcome", "to", "CSharp" };
object[] arr2 = arr1;
arr2[0] = 8;
}
}

출력:

C#의 예외 유형

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 정의됩니다. 그런 다음 문자열을 정의하고 값을 할당한 다음 객체 클래스 배열에 할당한 다음 정수를 동일한 배열에 넣으려고 시도하여 예외가 발생합니다.

5. System.IndexOutOfRangeException

메서드가 범위를 벗어난 배열을 참조할 때 생성되는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. IndexOutOfRangeException.

예:

//a class called check is defined
class check
{
//main method is called
static void Main()
{
// an array is defined to store 100 integers but then an integer is tried to be stores at a position outside of the size of the array which causes an exception
int[] arr = new int[10];
arr[0] = 10;
arr[10] = 20;
arr[20] = 30;
}
}

출력:

C#의 예외 유형

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 100개의 정수를 저장하도록 배열을 정의했지만 배열 크기를 벗어난 위치에 정수를 저장하려고 시도하여 예외가 발생했습니다.

6. System.DivideByZeroException

배당금을 0으로 나눌 때 발생하는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. DivideByZeroException.

예:

using System;
//a class called check is defined
class check
{
//main method is called
static void Main()
{
//an integer variable res is defined which is tried to divide by zero which causes an exception
int res = 10 / int.Parse("0");
Console.WriteLine(res);
}
}

출력:

C#의 예외 유형

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 예외를 발생시키는 0으로 나누려고 시도하는 정수 변수 res가 정의됩니다.

7. System.StackOverflowException

스택 오버플로로 인해 발생하는 오류는 이 예외로 처리됩니다. 시스템을 시연하기 위해 아래 예제 프로그램을 고려하십시오. StackOverflowException.

예:

using System;
//a class called check is defined
public class check
{
// a method called recurse is defined which takes a value as parameter and increases its value by one
static void Recurse(int val)
{
// since we have written a recursive loop and 0 is passed as a parameter, it ends in an infinite loop causing exception
Console.WriteLine(val);
Recurse(++val);
}
//main method is called
public static void Main()
{
//The recurse method is called to start the infinite recursion
Recurse(0);
}
} <strong>Output:</strong>

C#의 예외 유형

In the above program, a class called check is defined. Then a method called recurse is defined which takes a value as a parameter and increases its value by one. Then the main method is called in which the infinite loop for recursion begins by passing zero as a parameter. Then since we have written a recursive loop and 0 is passed as a parameter, it ends in an infinite loop causing an exception.

8. System.IO.IOException

The errors that are generated by input, the output is handled by this exception. Consider the below example program to demonstrate System. IO. IOException.

Example:

using System;
using System.IO;
//a class called check is defined
class check
{
//main methos is called
static void Main()
{
try
{
//a file is tried to open which do not exist and causes an exception
File.Open("D:\\ex.txt", FileMode.Open);
}
catch (IOException)
{
Console.WriteLine("Inputoutput Exception is handled");
}
}
}

Output:

C#의 예외 유형

In the above program, a class called check is defined. Then the main method is called. Then a file is tried to open which does not exist and causes an exception.

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

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