iT邦幫忙

DAY 24
0

Java重點學習筆記系列 第 24

Java重點筆記 21:野生旳Exceptions捕獲

在Java中捕捉Exceptions,可以用try/catch來完成。格式如下:

try
{
   //Code
}catch(ExceptionName e1)
{
   //Catch block
}

"Code"的部分是你想要監視的程式,一旦出現"ExceptionName"所指定的Exception,就會執行"Catch block"的程式。以下是例子:

import java.io.*;
public class ExcepTest{

   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}

結果顯示如下:

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

[image credit: PAULA BOROWSKA]


上一篇
Java重點筆記 20:列出目錄與文件
下一篇
Java重點筆記 22:捕捉多種Exceptions
系列文
Java重點學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言