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);
   }
}

输出结果

Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

多个尝试块:

您不能将多个try块与单个catch块一起使用。每个try块必须紧随catch或最后。但是,如果您尝试将单个catch块用于多个try块,则会生成编译时错误。

示例

以下Java程序尝试将单个catch块用于多个try块。

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);
      }catch(Exception ex) {
         System.out.println("Please pass the args while running the program");
      }
   }
}

编译时异常

ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations
   try {
   ^
1 error