標籤: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