在 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 程式碼塊。每個 try 程式碼塊後必須跟 catch 或 finally。仍然可以嘗試為多個 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);
      }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

更新於:2020-07-02

8K+ 次瀏覽

開啟您的職業生涯

完成課程以獲取認證

開始學習
廣告
© . All rights reserved.