About Exceptions in APCS JAVA

來源:互聯網
上載者:User

標籤:code   tps   mpi   normal   example   exce   static   struct   att   

什麼是Exceptions

首先我們要知道什麼是Exceptions, 定義如下

Exceptions: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

這是官方的定義,詳細請點擊

同時我們可以定義Exception為: An exception is an error condition that occurs during the execution of a Java Program.

這句話中兩個要點:1,exception 是一個 error(想想另外一個我們在APCS中會碰到的error --  compile error)

                          2,  occurs during the exectution,也就是在運行過程中出現的錯誤。

 

 

APCS 會考到哪些不同種類的Exceptions

Exceptions有非常多的種類,每一個種類的Exception 都有自己的一個名字由“出錯原因+Exception”組成。以下幾類將會在APCS中cover到。

1,ArithmeticExceptions

什麼情況會出現: Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero"

1 public class Test2 {   3     public static void main(String args[]){4         int x = 0;5         int y = 6;6         System.out.println("y/x = " + y/x); //6/0 will cause an ArithmeticException here7     }8 }

運行結果為

java.lang.ArithmeticException: / by zero
    at Test.main(Test.java:6)

 

2,NullPointerException

什麼情況會出現: Thrown when an application attempts to use null in a case where an object is required.

簡單說來就是當你想調用一個object的public方法或者使用public instance variable的時候這個object並沒有“存在”

 1 public class Test 2 {    3     private int x; 4     public int getX(){ 5         return x; 6     } 7      8     public static void main(String args[]){ 9         Test t = new Test();10         t = null;11         t.getX(); // may cause NullPointerException12     }13 }

運行結果為  

java.lang.NullPointerException
    at Test.main(Test.java:11)

 

 

3,ArrayIndexOutOfException

什麼情況會出現: Thrown when an application attempts to use null in a case where an object is required.

About Exceptions in APCS JAVA

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.