検索

次の記事では、Java の例外の種類の概要を説明します。 Java 例外は、プログラムの実行時に非常に重要な役割を果たします。一般的に、プログラムの実行時に異常終了または中断が発生すると、例外が発生します。 Java 例外は、例外が発生するたびにオブジェクトの作成時に発生します。Java はオブジェクト指向プログラミング言語であるため、実行時にエラーが発生し、例外はオブジェクトに関連します。したがって、例外とエラーの階層があり、スロー可能なブロック、try ブロック、catch ブロックを使用して、発生した例外をトラップして識別します。

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

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

Java のさまざまなタイプの例外

例外のタイプを担当する Java プログラムでのオブジェクトの作成は、次のように表される階層に従います。

Java の例外の種類

プログラミング中の Java の例外は、基本的に次の 2 つのカテゴリに分かれています:

  • 組み込み例外: これらは、既存の Java ライブラリを使用してキャッチできる例外のタイプです。これは、未チェック例外または実行時例外とも呼ばれます。
  • ユーザー定義の例外: これらは、ユーザーが作成したカスタマイズされた例外の一部を使用してキャッチできる例外のタイプであり、ユーザーはこれらの例外を処理できる必要があります。これらの例外は、チェック例外またはコンパイル時例外と呼ばれることもあります。

1.組み込み例外の種類

  • 算術例外
  • ClassNotFoundException
  • IO例外
  • ArrayIndexOutOfBoundsException
  • FileNotFoundException
  • NullPointerException
  • NoSuchFieldException
  • NoSuchMethodException
  • StringIndexOutOfBoundsException
  • ランタイム例外
  • NumberFormatException
  • 中断例外
a.算術例外

この例外は、算術計算時に何らかの不一致がある場合に呼び出されます。

例:

このプログラムは算術例外を示します。

コード:

public class Arithmtic_excpn {
public static void main(String[] args) {
{
try {
int first_no = 0;
int scnd_no = 20;
int third_no = 0;
int fourth_no = (first_no-scnd_no)/third_no;
System.out.println ("output after the operation " + fourth_no );
}
catch(ArithmeticException arithmetic_ex) {
System.out.println ("The third number cannot store the value of first number multiplied by second number.");
}
}
}
}

出力:

Java の例外の種類

b. ClassNotFoundException

クラスが適切に定義されていない場合、ClassNotFoundException が発生します。

例:

このプログラムは ClassNotFoundException を示します。

コード:

public class Not_Found_Excp {
private static final String mysql_connector = "com.jdbc.mysql-connector";
public static void main(String[] args) throws Exception {
System.out.println("search for the mysql-connector of jdbc for establishing connection.");
Class.forName(mysql_connector);
}
}

出力:

Java の例外の種類

c. IO 例外

入力または出力のいずれかが異常終了し、操作が失敗すると、IO 例外が発生します。

例:

このプログラムは IO 例外を示します。

コード:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class IO_Excption_Ex {
public FileInputStream testMethod1(){
File file_a = new File("123.txt");
FileInputStream fileInptstrm = null;
try{
fileInptstrm = new FileInputStream(file_a);
fileInptstrm.read();
}catch (IOException excpn){
excpn.printStackTrace();
}
finally{
try{
if (fileInptstrm != null){
fileInptstrm.close();
}
}catch (IOException excpn){
excpn.printStackTrace();
}
}
return fileInptstrm;
}
public static void main(String[] args){
IO_Excption_Ex inst_1 = new IO_Excption_Ex();
inst_1.testMethod1();
}
}

出力:

Java の例外の種類

d. ArrayIndexOutOfBoundsException

間違ったインデックスにアクセスし、インデックスの範囲が到達不能でアクセスできない場合は、ArrayIndexOutOfBoundsException が発生します

例:

このプログラムは ArrayIndexOutOfBoundsException を示します。

コード:

public class Arr_Indx_Out_Of_BOnd {
public static void main(String[] args) {
try{
int ar_0[] = new int[6];
ar_0[8] = 11;
}
catch(ArrayIndexOutOfBoundsException excp){
System.out.println ("Index of the array has crossed the range.");
}
}
}

出力:

Java の例外の種類

え。 FileNotFoundException

ファイルがパスに適切に指定されていない場合、または適切に開かれない場合は、FileNotFoundException がスローされます

例:

このプログラムは FileNotFoundException を示します。

コード:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class File_Not_Found_Excpt_Exmpl {
private static final String file_nm = "jkl.txt";
public static void main(String[] args) {
BufferedReader rder = null;
try {
rder = new BufferedReader(new FileReader(new File(file_nm)));
String inpt_ln = null;
while ((inpt_ln = rder.readLine()) != null)
System.out.println(inpt_ln);
} catch (IOException excpn) {
System.err.println("catch the IO Exception.");
excpn.printStackTrace();
} finally {
try {
rder.close();
} catch (IOException excpn) {
System.err.println("catch the IO Exception.");
excpn.printStackTrace();
}
}
}
}

出力:

Java の例外の種類

f. Null ポインタ例外

このタイプの例外は、オブジェクトのメンバーが null 値をポイントまたは参照するたびに発生します。

例:

このプログラムは、Null ポインター例外を示します。

コード:

public class Null_Pointer_Excp {
public static void main(String[] args) {
try {
String art_1 = null;
String art_3= "abc";
System.out.println(art_1.charAt(0));
} catch(NullPointerException excpn) {
System.out.println("This will give a null pointer exception.");
}
}
}

出力:

Java の例外の種類

g。 NoSuchFieldException

この例外は、フィールドが存在しない場合、または変数が存在しない場合に発生します。

例:

このプログラムは NoSuchFieldException を示します。

コード:

import java.text.DateFormat.Field;
import java.lang.reflect.*;
public class No_suc_field_excpn_Ex {
public static void main(String[] args) {
No_suc_field_excpn_Ex excp = new No_suc_field_excpn_Ex();
Class any_cls = excp.getClass();
System.out.println("value_of_field=");
try {
java.lang.reflect.Field strng_fld = any_cls.getField("One_strng");
System.out.println("field for the public superclass is found: " + strng_fld.toString());
} catch(NoSuchFieldException excpn) {
System.out.println(excpn.toString());
}
}
public No_suc_field_excpn_Ex() {
}
public No_suc_field_excpn_Ex(String One_strng) {
this.val_OneStrng = One_strng;
}
public String val_OneStrng = "Everything appears to be Exception.";
}

出力:

Java の例外の種類

h. NoSuchMethodException

While trying to access any method in a class and that method is not defined clearly or else is missing will lead to NoSuchMethodException.

Example:

This program demonstrates the NoSuchMethodException.

Code:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class No_Sch_mthd_Ex {
public static String add_rss;
public static String somefiletext;
public static String initial_page_src;
public static void Calculate() throws MalformedURLException {
URL url_a = new URL(add_rss) ;
URLConnection connect_2 = null;
try {
connect_2 = url_a.openConnection();
} catch (IOException excp) {
excp.printStackTrace();
}
BufferedReader buffrr = null;
try {
buffrr = new BufferedReader(
new InputStreamReader(connect_2.getInputStream()));
} catch (IOException excpn) {
excpn.printStackTrace();
}
String filnm_z = "C:\\Users\\adutta\\Documents\\"+"page_src"+"123.txt";
File file_o = new File(filnm_z);
if (!file_o.exists()) {
try {
file_o.createNewFile();
} catch (IOException excpn) {
excpn.printStackTrace();
}
}
FileWriter flwrtr = null;
try {
flwrtr = new FileWriter(filnm_z);
} catch (IOException exc) {
exc.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(flwrtr);
String textreader;
try {
while ((textreader = buffrr.readLine()) != null) {
bw.write(textreader);
}
} catch (IOException excn) {
excn.printStackTrace();
}
}
public static void set_page_src(String page_src){
page_src = initial_page_src;
}
public static void set_url(String addressname){
addressname = add_rss;
}
public static void set_text_file_name(String celeb_filename_p){
celeb_filename_p = celeb_name_i;
}
public static String celeb_name_i = "type_the_text" ;
public static  String url_add_ress = "http//ooo.com";
public static void main(String[] args) {
No_Sch_mthd_Ex.set_page_src(celeb_name_i);
No_Sch_mthd_Ex.set_url(url_add_ress);
try {
No_Sch_mthd_Ex.Calculate();
} catch (IOException excpn) {
excpn.printStackTrace();
}
}
}

Output:

Java の例外の種類

i. StringIndexOutOfBoundsException

If the index ranging is negative or more than the defined index range in the string class, then it will result into this exception of StringIndexOutOfBoundsException.

Example:

This program demonstrates the StringIndexOutOfBoundsException.

Code:

public class String_Inx_Out_Of_Bound_Ex {
public static void main(String[] args) {
try {
String ant = "ant crawls very slowly.";
char chrct = ant.charAt(50);
System.out.println(chrct);
}
catch(StringIndexOutOfBoundsException excepn) {
System.out.println("String_Out_Of_Bound_Exception occured.");
}
}
}

Output:

Java の例外の種類

j. RuntimeException

During runtime if any kind of exception arise then these types of exceptions are known as RuntimeException.

Example:

This program demonstrates the RuntimeException.

Code:

public class Runtime_Excp_Ex {
public void Demo_Runtime_Exception () {
throw new Running_Exception();
}
public static void main(String[] args) {
try {
new Running_Exception().Demo_Runtime_Exception();
} catch(Exception excpn) {
System.out.println(excpn.getClass().getName());
}
}
}
class Running_Exception extends RuntimeException {
public Running_Exception() {
super();
}
public void Demo_Runtime_Exception() {
throw new Running_Exception();
}
}

Output:

Java の例外の種類

k. NumberFormatException

Any exception which cannot get converted into numeric format from the string defined then it will lead to NumberFormatException.

Example:

This program demonstrates the NumberFormatException.

Code:

public class No_Format_Ex {
public static void main(String[] args) {
try {
int value1 = Integer.parseInt ("parasite1") ;
System.out.println(value1);
} catch(NumberFormatException excepn) {
System.out.println("This gives Number Format Exception");
}
}
}

Output:

Java の例外の種類

l. InterruptedException

If a thread gets disturbed at the time of waiting, sleeping or while performing some processing then it leads to interrupted Exception.

Example:

This program demonstrates the InterruptedException.

Code:

class ChildThread extends Thread {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException excpn) {
System.err.println("Interuppted_Exception occured.");
excpn.printStackTrace();
}
}
}
public class Interuupted_Excpt_Exmple {
public static void main(String[] args) throws InterruptedException {
ChildThread chldth1 = new ChildThread();
chldth1.start();
chldth1.interrupt();
}
}

Output:

Java の例外の種類

2. User-Defined Exception

This exception occurs whenever there is some customizable or errors done by user while implementation and execution of program.

Example:

This program demonstrates the user-Defined Exception.

Code:

public class My_Excpn extends Exception {
private static int roll_no[] = {10, 15, 23, 30};
private static String student_Nm[] = {"ani", "viky", "nidhi", "ash"};
private static double marks[] = {20.5, 44.6, 30, 17};
My_Excpn() {    }
My_Excpn(String str)
{
super(str);
}
public static void main(String[] args) {
try  {
System.out.println("roll_no" + "\t" + "student_Nm" +
"\t" + "marks");
for (int i = 0; i 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500559336989.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Java の例外の種類" ></p>
<h3 id="Conclusion">Conclusion</h3>
<p>Exceptions in java plays a very pivotal role because it helps in catching and simultaneously throwing of the root cause for an abnormal termination of the program. It often causes and consumes a lot of time for programmers to run and execute programs therefore these kinds of fatal exceptions should not occur frequently at the time of production or even implementation.</p>

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

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?高度なJavaプロジェクト管理、自動化の構築、依存関係の解像度にMavenまたはGradleを使用するにはどうすればよいですか?Mar 17, 2025 pm 05:46 PM

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?適切なバージョン化と依存関係管理を備えたカスタムJavaライブラリ(JARファイル)を作成および使用するにはどうすればよいですか?Mar 17, 2025 pm 05:45 PM

この記事では、MavenやGradleなどのツールを使用して、適切なバージョン化と依存関係管理を使用して、カスタムJavaライブラリ(JARファイル)の作成と使用について説明します。

カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?カフェインやグアバキャッシュなどのライブラリを使用して、Javaアプリケーションにマルチレベルキャッシュを実装するにはどうすればよいですか?Mar 17, 2025 pm 05:44 PM

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPA(Java Persistence API)を使用するにはどうすればよいですか?Mar 17, 2025 pm 05:43 PM

この記事では、キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPAを使用することについて説明します。潜在的な落とし穴を強調しながら、パフォーマンスを最適化するためのセットアップ、エンティティマッピング、およびベストプラクティスをカバーしています。[159文字]

Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Javaのクラスロードメカニズムは、さまざまなクラスローダーやその委任モデルを含むどのように機能しますか?Mar 17, 2025 pm 05:35 PM

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します

分散コンピューティングにJavaのRMI(リモートメソッドの呼び出し)を使用するにはどうすればよいですか?分散コンピューティングにJavaのRMI(リモートメソッドの呼び出し)を使用するにはどうすればよいですか?Mar 11, 2025 pm 05:53 PM

この記事では、分散アプリケーションを構築するためのJavaのリモートメソッドの呼び出し(RMI)について説明します。 インターフェイスの定義、実装、レジストリのセットアップ、およびクライアント側の呼び出しを詳述し、ネットワークの問題やセキュリティなどの課題に対処します。

ネットワーク通信にJavaのソケットAPIを使用するにはどうすればよいですか?ネットワーク通信にJavaのソケットAPIを使用するにはどうすればよいですか?Mar 11, 2025 pm 05:53 PM

この記事では、ネットワーク通信のためのJavaのソケットAPI、クライアントサーバーのセットアップ、データ処理、リソース管理、エラー処理、セキュリティなどの重要な考慮事項をカバーしています。 また、パフォーマンスの最適化手法も調査します

Javaでカスタムネットワークプロトコルを作成するにはどうすればよいですか?Javaでカスタムネットワークプロトコルを作成するにはどうすればよいですか?Mar 11, 2025 pm 05:52 PM

この記事では、カスタムJavaネットワーキングプロトコルの作成を詳述しています。 プロトコルの定義(データ構造、フレーミング、エラー処理、バージョン化)、実装(ソケットを使用)、データシリアル化、およびベストプラクティス(効率、セキュリティ、メンテナ

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SublimeText3 中国語版

SublimeText3 中国語版

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