ついにJavaで

WBOY
リリース: 2024-08-30 16:15:28
オリジナル
408 人が閲覧しました

次の記事では、Final in Java の概要を説明します。最後に、try および catch とともに使用されるコードのブロックです。最後に、例外が発生するかどうかに関係なく実行する必要があるコードのブロックが含まれます。 finally ブロック内に記述されたステートメントは、try ブロックでエラーが発生したかどうかに関係なく、常に実行されます。最後に、このブロックは、ファイルを開いていることによるメモリ エラーや、オープン接続や最大接続エラーによるデータベース エラーが発生しないようにする、ファイルやデータベース接続を閉じるのに適しています。また、コード内で発生したエラーが適切に処理されるようになります。

広告 このカテゴリーの人気コース 財務モデリングと評価 - 専門分野 | 51 コースシリーズ | 30 回の模擬テスト

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

構文:

try {
//block of code that may cause an exception
}
ログイン後にコピー
catch {
//Handling the error occurred in try block
}
ログイン後にコピー
finally {
//code that should always execute
}
ログイン後にコピー

Java では Final はどのように動作しますか?

ここでは、エラーをスローするか、エラーを引き起こして最終的に実行をブロックするエラーコードを記述します。

コード:

class ExampleFinally
{
public static void main(String args[]) {
try{
int result = 1/0;
System.out.println(result);
catch(ArithmeticException e){
System.out.println("Divide by Zero Error");
}
/* Finally block will always execute
* even when we have created an error
Block */
finally{
System.out.println("Gracefully Handling Error in Finally");
}
System.out.println("Execution complete out of Try Catch Finally block");
}
}
ログイン後にコピー

出力:

ついにJavaで

説明:

上記のプログラムでは、すでに数値をゼロから除算しています。

  • Finally でエラーを適切に処理します。

そして最後に try catch の後で、印刷されるすべての外側にコードのブロックを書きました。

  • Try Catch Final ブロッ​​クからの実行が完了しました。

もう 1 つの例では、try-catch-finally ブロック内で例外が発生しない場所を確認し、何が起こるかを確認します。

コード:

class ExampleFinally
{
public static void main(String args[]) {
try
{  int result = 100/10;
System.out.println(result);
System.out.println("try code block");
}
catch (Exception e)
{
System.out.println("catch code block");
}
finally
{
System.out.println("finally code block");
}
}
}
ログイン後にコピー

出力:

ついにJavaで

説明:

上記のプログラムでは、エラーを引き起こす可能性のあるコードは一切記述していません。コードは try ブロック内で正常に実行されましたが、それでも、finally ブロックが実行され、内部でメッセージが出力されたことがわかります。

  • ついにコードブロック

最後に、Java プログラムでの使用をブロックします

読み取りまたは書き込みのためにファイルを開くには、ファイルを開いてからストリームをバッファリングする必要があります。また、ファイル処理、IO、またはディスク エラーが発生しないように、開いたファイルを必ず閉じる必要があります。

コード:

import java.io.*;
public class ReadingFromFile
{
public static void main(String[] args)throws Exception
{
FileReader fr = null;
try {
fr = new FileReader("/Users/cdp/Documents/testing/python virtual/java/myfile.txt");<>
System.out.println("Opening the file");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
System.out.println("Closing the file ");
fr.close();
} catch (IOException e) {
System.out.println("unrecoverable Error occurred");
e.printStackTrace();
}
}
System.out.println("Exiting Finally block");
}
}
}
ログイン後にコピー

出力 (ファイルが存在しません):

ついにJavaで

出力 (ファイルが存在します):

ついにJavaで

上記の例では、ファイルを開いてファイル パスからバッファにそれを読み取ろうとしました。ファイルが存在し、ファイルを読み取ることができる場合、エラーはスローされず、ファイル バッファーが null でない場合は、finally ブロックで閉じられます。ファイルの読み取り中にエラーが発生した場合でも、たとえば何らかの権限が原因で、finally ブロックでもファイルが閉じられます。

重要性

  • 最後に、ブロックは常に try ブロックに関連付けられている必要があります。 try ブロックがなければ usefinally ブロックを書くことはできません。 finally ブロック内に記述したステートメントは、エラーが発生するかどうかに関係なく、try ブロックのコードに常に依存せずに実行されます。
  • 最後に、このブロックは必須のブロックではありません。 finally ブロックを使わずに try および catch ブロックを書くことができます。入力にバグがあるユーザー入力のエラーをキャッチしたいだけだとしましょう。
  • それでもエラーが発生していない場合、最終的にブロックが実行されます。エラーがある場合は、最初の catch ブロックが実行され、次に最後に実行されます。
  • finally ブロックでは、すべての例外が同じ動作をします。ブロックはすべての例外に対して通常どおり実行されます。
  • 最後に、try ブロック内に Break、return、または continue ステートメントがある場合でも、ブロックは実行されます。

最終的に実行されなくなるのはどのような場合ですか?

これまで、最終的にブロックがいつ、どのように実行されるかを見てきました。

ただし、特定のシナリオでは、最終的にブロックが実行されない可能性があります。

  • There could be a thread getting executed; it is most likely to be the main thread where program execution is happening, and abruptly it dies, then the finally block won’t be getting executed.
  • If in the try or catch block we have used System class with the exit method that is System.exit(), then the whole system would exit, and no control will be transferred to the next block of code.
  • If finally only throws an exception, then the program would not exit gracefully but exit abruptly.

Example:

import java.io.*;
public class ReadingFromFile
{
public static void main(String[] args)throws Exception
{
FileReader fr = null;
try {
fr = new FileReader("/Users/cdp/Documents/testing/python virtual/java/myfile.txt");
System.out.println("Opening the file");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
System.exit(0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
System.out.println("Closing the file ");
fr.close();
} catch (IOException e) {
System.out.println("unrecoverable Error occurred");
e.printStackTrace();
}
}
System.out.println("Exiting Finally block");
}
}
}
ログイン後にコピー

Output:

ついにJavaで

In the above example, we have used System.exit in the try block after reading the file, and it gets executed. If the System.exit gets executed without any exception, then there won’t be any control transfer to the finally block. However, in the case of an exception occuring before the System.exit, then finally block would surely get executed.

Conclusion

In the conclusion we can reach, it can finally play a very important role in gracefully exiting the program in case of errors. Finally, the block is important when you open a connection or buffered something, and it’s always important to close the connection or file opened. Finally, the block would even execute if there is an error or no error in the try block code. Finally, blocks are not mandatory but are useful in some situations.

以上がついにJavaでの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!