Java 中,多个 try 块可以只包含一个 catch 块吗?

java 8object oriented programmingprogramming

异常是指程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的代码行之后的代码将永远不会被执行。

示例

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 块。每个 try 块后面必须跟 catch 或 finally。但是,如果您尝试将单个 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

相关文章