C# での例外処理
Sep 03, 2024 pm 03:20 PMユーザーが常に正しい詳細を入力することは期待できません。ただし、間違った入力または予期しない入力が正しく処理されない場合、コード全体がクラッシュしたり、無限ループに陥ったりする可能性があります。これは、プログラムの実行中に予期せぬ条件や入力によって発生する問題です。たとえば、数値をゼロで除算すると、結果は無限になります。例外処理は、コードの次のブロックに進むか、特定の状況で定義された結果を提供するようにプログラムに指示する方法です。
C# の例外処理のキーワード
以下の 4 つのキーワードを使用して例外処理を行うことができます。
- Try: try ブロックは、処理される例外のタイプを定義します。ここで例外がキャッチされます。常に 1 つの catch ブロックとペアになります。
- Catch: try ブロックが型を定義し、実行中に 1 つの例外を取得すると、catch ブロックは使用する例外ハンドラーの型を確認します。このブロックは、例外を処理する場所も決定します。キーワードが示すように、例外をキャッチするようなものです。
- 最後に: このブロックにはいくつかのステートメントのセットがあります。例外がスローされるかどうかに関係なく、最後のブロックで定義されたステートメントは常に実行されます。
- Throw: 例外がキャッチされた場合、キャッチされた例外を表示するために throw キーワードが使用されます。
例外ハンドラーを定義すると、ソフトウェアやコードを多くの手間から省くことができます。例外が発生する可能性がある場合は常に例外ハンドラーを定義することをお勧めします。
構文:
例外が発生するたびに、宣言されたメソッドは try および catch キーワードを使用して例外をキャッチします。この組み合わせをコードの一部に配置する必要があるため、例外が発生することが予想されます。これらのコードは保護されたコードと呼ばれます。 1 つの 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 は例外がキャッチされたときに何を行うかを確認します。ブロックの最後の部分は、例外が検出されたかどうかに関係なく実行する必要がある内容を定義し、throw 部分は、設定されている場合はメッセージを表示します。
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 |
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# 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:
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:
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:
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:
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 中国語 Web サイトの他の関連記事を参照してください。

人気の記事

人気の記事

ホットな記事タグ

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









