English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Javaでは、catchブロックが複数のtryブロックを持つ可能性はありますか?

例外はプログラムの実行中に発生する問題(ランタイムエラー)です。例外が発生すると、プログラムは突然終了し、例外が発生した行の次のコードは決して実行されません。

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: "+c);
   }
}

出力結果

第一の数を入力してください:
100
第二の数を入力してください:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

複数の試行ブロック:

複数のtryブロックは単一のcatchブロックと一緒には使用できません。各tryブロックはcatchまたは最後にすぐに続く必要があります。ただし、複数のtryブロックに対して単一のcatchブロックを使用しようと試みると、コンパイル時エラーが発生します。

以下のJavaプログラムは、複数のtryブロックに対して単一のcatchブロックを使用しようと試みています。

class ExceptionExample{
   public static void main(String args[]) {
      int a,b;
      try {
         a=Integer.parseInt(args[0]);
         b=Integer.parseInt(args[1]);
      }
      try {
         int c=a/b;
         System.out.println(c);
      }
         System.out.println("Please pass the args while running the program");
      }
   }
}

コンパイル時エラー

ExceptionExample.java:4: エラー: 'try' が 'catch'、'finally' またはリソース宣言なしで使用されています
   try {
   ^
1 エラー
おすすめ