当前位置:首页 > 服务端 > JAVA 8学习笔记-第六章

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");

}

 

作者:小白闯天涯
来源链接:https://www.cnblogs.com/shendehong/p/11681746.html

版权声明:
1、Java侠(https://www.javaxia.com)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaxia.com/server/124672.html

分享给朋友:

“JAVA 8学习笔记-第六章” 的相关文章

软件工程复习要点2022年05月17日 14:38:01
[C#][控件]常用控件命名规范2022年05月17日 20:45:24
Logger的级别2022年05月19日 20:04:12
Spring Boot+微信小程序2022年05月20日 21:27:40
Python 树表查找2022年05月20日 21:28:27
软件工程专业如何就业!2022年05月23日 22:31:42
信息系统合同管理2022年05月24日 22:14:31