JAVA 8学习笔记-第六章
CHAPTER 6 EXCEPTIONS
Any Java type can be declared as the return type, including exception.
The key point is to remember that exceptions alter the program flow.
example:
output result:
AECException in thread "main" java.lang.NullPointerException
at DoSomething.stop(DoSomething.java:16)
at DoSomething.go(DoSomething.java:5)
at DoSomething.main(DoSomething.java:20)
public class DoSomething {
public void go() {
System.out.print("A");
try {
stop();
} catch (ArithmeticException e) { // if changed to NullPointerException, result is AEBCD
System.out.print("B");
} finally {
System.out.print("C");
}
System.out.print("D"); // NullPointerException is not catched, the go() terminates without excuting this line
}
public void stop() {
System.out.print("E");
Object x = null;
x.toString(); // NullPointerException occurs, stop() terminates
System.out.print("F");
}
public static void main(String[] args) {
new DoSomething().go();
}
}
1. Exception Type
- unchecked exception: RuntimeException class and its subclass, can be catched by program, but is NOT required to declare or handle
- checked exception: Exception and its subclasses that do not extend RuntimeException, required to declare or handle
- error: can NOT be catched by program, and is NOT required to declare or handle
void fall() throws Exception{ // declares that the method might throw an Exception
throw new Exception(); // tells JAVA that you want to throw an Exception
}
2. Try Statement
JAVA uses a try statement to separate the logic that may throw an exception from the logic to handle that exception.
try{}
catch(exceptiontype e){}
// excutes only matches the exception thrown by the code in the try block, do NOT catch exception thrown by other catch clause
finally{} // always excutes whether or not an exception occurs in the try statement
When System.exit(0) is called in the try or catch block, the finally does NOT run.
3. Catch Various Types of Exceptions
Compile error happens if a superclass exception is catched before a subclass exception.
example:
class Closed extends RuntimeException{}
try{
see animal();
} catch(RuntimeException e){
System.out.println("try later");
}catch(Closed e){ // compile error, cause Closed is a subclass of RuntimeException, it should appear before RuntimeException
Sytem.out.println("try again"):
}
Only the last exception thrown matters.
try{
throw new RuntimeException();
}catch (RuntimeException e){
throw new RuntimeException():
}finally{
throw new Exception(); // only this exception is thrown out.
}
4. Runtime Exceptions
Allowed to be declared and handled, but not required.
Methods are free to throw any runtime exceptions they want without mentioning them in the method declaration.
public void ohNO() throws IOException{
throw new RuntimeException(); //OK
throw new NullPointerException(); //OK
throw new Exception(); // compile error
}
- ArithmeticException: divided by zero, thrown by JVM
- ArrayIndexOutOfBoundsException: illegal index to access an array, thrown by JVM
- ClassCastException: cast a class to a subclass which it is not an instance of the subclass, thrown by JVM
- IllegalArgumentException: method is passed in an illegal argument, thrown by programmer
- NullPointerException: null reference where an object is required, thrown by JVM
Instance variables and methods must be called on an non-null reference.
- NumberFormatException: subclass of IllegalArgumentException, occurs when convert a string to an number but the string does NOT have a appropriate formate, thrown by programmer
Integer.parseInt("abc");
5. Checked Exceptions
Must be declared or handled.
try{
System.out.println("hello");
}catch(IOException e){ // compile error, cause the method in the try block never throws IOException, it's unreachable code.
}
FileNotFoundException: try to refer to an file that does not exist, subclass of IOException, thrown programatically
IOException: there is problem reading or writing a file, thown programatically
6. Errors
Allowed to declared or handled. But should NOT be declared or handled.
ExceptionInInitializerError: static initialier throws an exception and does not handle it, thrown by JVM
static{
int[] count = new int[3];
int num = count[-1]; // error
}
StackOverflowError: calles itself many times (infinite recursion), thrown by JVM
do(int num){
do(1);
}
NoClassDefFoundError: a class available in compile but not runtime, thrown by JVM
7. Calling Methods That Throw Exceptions
Rules are same as within a method: declare or handle it for checked exceptions
example 1:
class NoMoreException extends Exceptoin{}
public class Bunny{
public static void main(String[] args){
eatCarrot(); // compile error
}
private static void eatCarrot() throws NoMoreException{}
}
can be solved by the following:
solution 1: declare it
public static void main (String[] args) throws NoMoreException{ //declare exception
eatCarrot();
}
solution 2: handle it
public static void main (String[] args){
try{
eatCarrot();
} catch (NoMoreException e){ // handle exception
System.out.println("bad rabbit"):
}
}
example 2:
class NoMoreException extends Exception{}
public static void main (String[] args){
try{
eatCarrot();
} catch (NoMoreException e){ // compile error cause it is unreachable code
System.out.println("bad rabbit"):
}
public static good() throws NoMoreException{ // OK
eatCarrot();
}
public static void eatCarrot(){}
}
8. Subclass - overrides method
Methods are free to throw any runtime exceptions they want without mentioning them in the method declaration.
class IllegalStateException extend RuntimeException{}
class Hopper{
public void hop(){}
}
class Bunny extends Hopper{
public void hop() throws IllegalStateException{} //OK
}
Rules for checked exceptions:
- NOT permitted to throw new exception in subclass
class CanNotHopException extends Exception{}
class Hopper{
public void hop(){}
}
class Bunny extends Hopper{
public void hop() throws CanNotHopException {} // compile error
}
- allowed to declare fewer exception in subclass
class Hopper{
public void hop() throws CanNotHopException{}
}
class Bunny extends Hopper{
public void hop() {}
}
- allowed to declare a subclass of an exception type
class Hopper{
public void hop() throws Exception{}
}
class Bunny extends Hopper{
public void hop() throws CanNotHopException{}
}
9. Print an Exception
When writing your code, print out a stack trace or at least a message when catching an exception. Don't Handle it poorly.
Three ways to print:
- let Java print it
- print the message
- print where the stack trace comes from
try{ hop() }
catch(Exception e){
System.out.println(e); // java.lang.RuntimeException: can no hop
System.out.println(e.getMessage()); // can not hop
e.printStackTrace(); // at trycatch......
}
void hop(){
throw new RuntimeException("can not hop");
}