首页 > 代码库 > About Exceptions in APCS JAVA
About Exceptions in APCS JAVA
什么是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