一般的なJavaの例外

一般的なJavaの例外

1. 前書き

このチュートリアルでは、いくつかの一般的なJava例外に焦点を当てています。

まず、基本的に例外とは何かについて説明します。 後で、さまざまな種類のチェックされた例外とチェックされていない例外について詳しく説明します。

2. 例外

An exception is an abnormal condition that occurs in a code sequence during the execution of a program.この異常な状態は、プログラムが実行時に特定の制約に違反した場合に発生します。

すべての例外タイプは、クラスExceptionのサブクラスです。 次に、このクラスは、チェック済み例外と未チェック例外にサブクラス化されます。 これらについては、以降のセクションで詳しく説明します。

3. チェック済みの例外

Checked exceptions are mandatory to handle.これらはクラスExceptionの直接のサブクラスです。

それらの重要性には、一見の価値があるdebateがあります。

いくつかのチェックされた例外を詳細に定義しましょう。

3.1. IOException

入出力操作が失敗すると、メソッドはIOExceptionまたはその直接のサブクラスをスローします。  

これらのI / O操作の一般的な用途は次のとおりです。

  • java.ioパッケージを使用したファイルシステムまたはデータストリームの操作

  • java.netパッケージを使用したネットワークアプリケーションの作成

FileNotFoundException

FileNotFoundExceptionは、ファイルシステムでの作業中の一般的なタイプのIOExceptionです。

try {
    new FileReader(new File("/invalid/file/location"));
} catch (FileNotFoundException e) {
    LOGGER.info("FileNotFoundException caught!");
}

MalformedURLException

URLを操作するときに、URLが無効な場合、MalformedURLException – が発生する可能性があります。

try {
    new URL("malformedurl");
} catch (MalformedURLException e) {
    LOGGER.error("MalformedURLException caught!");
}

3.2. ParseException

Javaはテキスト解析を使用して、指定されたString.If parsing causes an error, it throws a ParseException.に基づいてオブジェクトを作成します

たとえば、Dateをさまざまな方法で表すことができます。 dd/mm/yyyyまたはdd,mm,yyyy,ですが、別の形式でstringを解析してみてください。

try {
    new SimpleDateFormat("MM, dd, yyyy").parse("invalid-date");
} catch (ParseException e) {
    LOGGER.error("ParseException caught!");
}

ここで、Stringは不正な形式であり、ParseExceptionを引き起こします。

3.3. InterruptedException

Javaスレッドがjoin(), sleep()またはwait()を呼び出すと、WAITING状態またはTIMED_WAITING状態になります。

さらに、スレッドは、別のスレッドのinterrupt()メソッドを呼び出すことにより、別のスレッドに割り込むことができます。

したがって、the thread throws an InterruptedException if another thread interrupts it while it is in the WAITING or in the TIMED_WAITING state.

2つのスレッドがある次の例を考えてみましょう。

  • メインスレッドは子スレッドを開始し、割り込みます

  • 子スレッドが開始し、sleep()を呼び出します

このシナリオでは、InterruptedException:になります

class ChildThread extends Thread {

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOGGER.error("InterruptedException caught!");
        }
    }
}

public class MainThread {

    public static void main(String[] args)
      throws InterruptedException {
        ChildThread childThread = new ChildThread();
        childThread.start();
        childThread.interrupt();
    }
}

4. 未確認の例外

For Unchecked Exceptions, the compiler doesn’t check during the compilation process.したがって、メソッドがこれらの例外を処理することは必須ではありません。

チェックされていないすべての例外は、クラスRuntimeException.を拡張します

いくつかの未チェックの例外について詳しく説明しましょう。

4.1. NullPointerException

アプリケーションが実際にオブジェクトインスタンスを必要とする場所でnullを使用しようとすると、メソッドはNullPointerExceptionをスローします。

nullの不正使用がNullPointerException.を引き起こすさまざまなシナリオがあります。それらのいくつかを考えてみましょう。

オブジェクトインスタンスを持たないクラスのメソッドを呼び出す:

String strObj = null;
strObj.equals("Hello World"); // throws NullPointerException.

また、アプリケーションがnull参照を使用してインスタンス変数にアクセスまたは変更しようとすると、NullPointerException:が取得されます。

Person personObj = null;
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Jon Doe"; // Modifying the field of a null object

4.2. ArrayIndexOutOfBoundsException

配列は、要素を連続して格納します。 したがって、インデックスを介してその要素にアクセスできます。

ただし、, if a piece of code tries to access an illegal index of an array, the respective method throws an ArrayIndexOutOfBoundException.

ArrayIndexOutOfBoundExceptionをスローするいくつかの例を見てみましょう。

int[] nums = new int[] {1, 2, 3};
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4];   // Trying to access at greater index
int numFromLengthIndex = nums[3];    // Trying to access at index equal to size of the array

4.3. StringIndexOutOfBoundsException

JavaのStringクラスは、文字列の特定の文字にアクセスしたり、String.から文字配列をスライスしたりするためのメソッドを提供します。これらのメソッドを使用すると、内部でStringが変換されます。文字配列に。

繰り返しますが、この配列でインデックスが不正に使用される可能性があります。 このような場合、Stringクラスのこれらのメソッドは、StringIndexOutOfBoundsExceptionをスローします。

この例外indicates that the index is either greater than or equal to the size of the String. StringIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionを拡張します。

クラスStringのメソッドcharAt(index)は、String’sの長さに等しいインデックスまたはその他の不正なインデックスの文字にアクセスしようとすると、この例外をスローします。

String str = "Hello World";
char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
char charAtLengthIndex = str.charAt(11);   // Trying to access at index equal to size of the string

4.4. NumberFormatException

多くの場合、アプリケーションはStringの数値データで終了します。 このデータを数値として解釈するために、JavaではStringを数値タイプに変換できます。 Integer, Float, etc.などのラッパークラスには、この目的のためのユーティリティメソッドが含まれています。

ただし、if the String doesn’t have an appropriate format during the conversion, the method throws a NumberFormatException.

次のスニペットについて考えてみましょう。

ここでは、英数字データを使用してStringを宣言します。 さらに、Integerラッパークラスのメソッドを使用して、このデータを数値として解釈しようとします。

その結果、これはNumberFormatException:になります

String str = "100ABCD";
int x = Integer.parseInt(str); // Throws NumberFormatException
int y = Integer.valueOf(str); //Throws NumberFormatException

4.5. ArithmeticException

When a program evaluates an arithmetic operation and it results in some exceptional condition, it throws ArithmeticException.さらに、ArithmeticExceptionint およびlongデータ型にのみ適用されます。

たとえば、整数をゼロで除算しようとすると、ArithmeticExceptionが得られます。

int illegalOperation = 30/0; // Throws ArithmeticException

4.6. ClassCastException

Javaは、継承とポリモーフィズムをサポートするために、オブジェクト間のtypecastingを許可します。 オブジェクトをアップキャストまたはダウンキャストできます。

アップキャストでは、オブジェクトをそのスーパータイプにキャストします。 ダウンキャストでは、オブジェクトをそのサブタイプの1つにキャストします。

ただし、at runtime, if the code attempts to downcast an object to a subtype of which it isn’t an instance, the method throws a ClassCastException.

実行時インスタンスは、型キャストで実際に重要なものです。 AnimalDog, and Lionの間の次の継承について考えてみます。

class Animal {}

class Dog extends Animal {}

class Lion extends Animal {}

さらに、ドライバークラスでは、Lionのインスタンスを含むAnimal参照をDogにキャストします。

ただし、実行時に、JVMはインスタンスLionがクラスDogのサブタイプと互換性がないことに気付きます。

これにより、ClassCastException:になります

Animal animal = new Lion(); // At runtime the instance is Lion
Dog tommy = (Dog) animal; // Throws ClassCastException

4.7. IllegalArgumentException

不正または不適切な引数を指定してメソッドを呼び出すと、メソッドはIllegalArgumentExceptionをスローします。

たとえば、Threadクラスのsleep()メソッドは正の時間を予期し、引数として負の時間間隔を渡します。 これにより、IllegalArgumentExceptionになります。

Thread.currentThread().sleep(-10000); // Throws IllegalArgumentException

4.8. IllegalStateException

IllegalStateExceptionは、メソッドが違法または不適切な時間に呼び出されたことを示します。

すべてのJavaオブジェクトには、状態(インスタンス変数)といくつかの動作(メソッド)があります。 したがって、IllegalStateExceptionは、現在の状態変数を使用してこのオブジェクトの動作を呼び出すことは違法であることを意味します。

ただし、いくつかの異なる状態変数では、正当な場合があります。

たとえば、反復子を使用してリストを反復します。 初期化するたびに、内部的に状態変数lastRetを-1に設定します。

このコンテキストで、プログラムはリストのremoveメソッドを呼び出そうとします。

//Initialized with index at -1
Iterator intListIterator = new ArrayList<>().iterator();

intListIterator.remove(); // IllegalStateException

内部的には、removeメソッドは状態変数lastRetをチェックし、それが0未満の場合、IllegalStateException. をスローします。ここで、変数はまだ値-1を指しています。

その結果、IllegalStateExceptionが得られます。

5. 結論

この記事では、まず例外について説明しました。 exceptionは、プログラムの実行中に発生するイベントであり、プログラムの命令の通常のフローを中断します。

次に、例外をChecked ExceptionsとUnchecked Exceptionsに分類しました。

次に、コンパイル時または実行時に発生する可能性のあるさまざまな種類の例外について説明しました。

この記事over on GitHubのコードを見つけることができます。