C#의 예외 처리

WBOY
풀어 주다: 2024-09-03 15:20:23
원래의
955명이 탐색했습니다.

사용자가 항상 정확한 세부정보를 입력할 것이라고 기대할 수는 없습니다. 그러나 올바르지 않거나 예상치 못한 입력이 올바르게 처리되지 않으면 전체 코드가 충돌하거나 무한 루프가 발생할 수 있습니다. 프로그램 실행 중 예상치 못한 조건이나 입력으로 인해 발생하는 문제입니다. 예를 들어, 숫자를 0으로 나누면 결과는 무한합니다. 예외 처리는 프로그램이 다음 코드 블록으로 이동하도록 지시하거나 특정 상황에서 정의된 결과를 제공하는 방법입니다.

C# 예외 처리 키워드

아래의 4가지 키워드로 예외처리가 가능합니다.

  1. Try: try 블록은 처리할 예외 유형을 정의합니다. 여기서 예외가 발생합니다. 항상 하나의 캐치 블록과 쌍을 이룹니다.
  2. Catch: try 블록이 유형을 정의하고 실행 중에 하나의 예외를 받으면 catch 블록은 사용할 예외 처리기의 유형을 확인합니다. 이 블록은 예외를 처리할 위치도 결정합니다. 키워드에서 알 수 있듯이 예외를 잡는 것과 같습니다.
  3. 마지막으로: 이 블록에는 몇 가지 명령문 세트가 있습니다. 예외가 발생하더라도 마지막 블록에 정의된 명령문은 항상 실행됩니다.
  4. Throw: 예외가 catch되면 throw 키워드를 사용하여 잡힌 예외를 표시합니다.

예외 처리기를 정의하면 소프트웨어나 코드의 번거로움을 덜 수 있습니다. 예외가 발생할 수 있는 곳마다 예외 처리기를 정의하는 것이 좋습니다.

구문:

예외가 발생할 때마다 선언된 메서드는 try 및 catch 키워드를 사용하여 예외를 포착합니다. 이 조합을 코드 부분에 배치해야 하며 예외가 예상됩니다. 이러한 코드를 보호 코드라고 합니다. 하나의 try 키워드에 대해 둘 이상의 catch 키워드를 정의할 수도 있습니다. 콘텐츠가 끝나면 코드의 마지막 부분이 실행되어 예외 발생 여부와 관계없이 실행됩니다.

코드:

try
{
//Define the statement that could cause an exception.
}
Catch(ExceptionName secondException)
{
//error handling code
}
Finally
{
//define the statement that will be executed
}
로그인 후 복사

C#에서 예외 처리는 어떻게 작동하나요?

예외 처리를 위해 사전 정의된 클래스가 많이 있습니다. try 블록은 예외를 발생시킬 수 있는 코드 부분을 다루고, catch는 예외가 발견될 때 수행할 작업을 확인합니다. 블록의 마지막 부분은 예외가 감지되었는지 여부에 관계없이 수행해야 할 작업을 정의하고 발생 부분은 설정된 경우 메시지를 표시합니다.

C#의 예외 클래스

C#에는 예외를 표현할 수 있는 클래스가 많이 있습니다. 모든 클래스는 System이라는 기본 클래스에서 파생됩니다. 예외. System.ApplicationException 및 System.SystemException에서도 파생되는 클래스가 거의 없습니다.

C#의 예외 클래스 예

예외는 시스템에서 파생됩니다. 예외 클래스. C# 공통 예외 클래스 목록은 다음과 같습니다.

                   Exception                    Description
System.DivideByZeroException handles the error when trying to divide a number by zero.
System.NullReferenceException handles the error when referring to an object which does not exist.
System.InvalidCastException handles the error when trying invalid casting.
System.IO.IOException All input-output error is handled.
System.FieldAccessException When trying to access unauthorized class
                   예외                    설명 System.DivideByZeroException 숫자를 0으로 나누려고 할 때 발생하는 오류를 처리합니다. System.NullReferenceException 존재하지 않는 개체를 참조할 때 발생하는 오류를 처리합니다. System.InvalidCastException 잘못된 캐스팅을 시도할 때 오류를 처리합니다. System.IO.IO예외 모든 입출력 오류가 처리됩니다. System.FieldAccessException 승인되지 않은 수업에 접속하려고 할 때

1. C# try/catch

Exception handling is done by try and catches block in C#. The try block in C# is used to place the code that may throw an exception. The exception is handled by the catch block.

C# example without try/catch

Code:

using System;
public class exceptionhandling
{
public static void Main(string[] args)
{
int a = 10;
int b = 0;
int x = a/b;    //we are trying to divide the number with zero
Console.WriteLine("other part of the code");
}
}
로그인 후 복사

Output:
C#의 예외 처리

C# try/catch example

Code

using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}
로그인 후 복사

Output:
C#의 예외 처리

Use of Exception Classes in C# finally

It will show you the message regardless the exception is caught.

Code

using System;
public class Exceptionhandling
{
public static void Main(string[] args)
{
try
{
int x = 5;
int y= 0;
int z = x / y;
}
catch (Exception obj) { Console.WriteLine(obj); }
finally { Console.WriteLine("Time to execute finally block"); }
Console.WriteLine("Other part of the code");
}
}
로그인 후 복사

Output:
C#의 예외 처리

1. C# finally example if Exception is not handled

Code

using System;
public class ExceptionHandling
{
public static void Main(string[] args)
{
try
{
int p = 6;
int q = 0;
int r= p/q;
}
catch (NullReferenceException nullObject) { Console.WriteLine(nullObject); }
finally { Console.WriteLine("Exception not handled. Now Finally section will be executed"); }
Console.WriteLine("Other part of the code");
}
}
로그인 후 복사

Output:
C#의 예외 처리

2. C# user-defined Exception

The not only system defined, but we can also set our own exception. However, we need to inherit the code in order to get this done.

Code

using System;
public class userdefinedInvalidAge : Exception
{
public userdefinedInvalidAge (String errorMessage)
: base(errorMessage)
{
}
}
public class TestUserDefinedException
{
static void validateAge(int age)
{
if (age < 18)
{
throw new userdefinedInvalidAge("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validateAge(12);
}
catch (userdefinedInvalidAge e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}
로그인 후 복사

Output:
C#의 예외 처리

Conclusion

At any place you think it might generate an error because of anything, exception handler should be used. It is essential that you use a catch statement and start from generic to a specific exception. Your entire software or code is at risk without proper exception handler.

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

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!