Java的异常处理Exceptions Handling-笔记

来源:互联网 发布:linux如何取得root权限 编辑:程序博客网 时间:2024/05/19 03:46

Java - Exceptions Handling

本文参考这里

三类异常:

  • Checked exceptions:编译时可检查的异常
  • Runtime exceptions:运行时异常
  • Errors:发生错误

异常的体系(Exception Hierarchy)

  • Throwable
    • Exception
      • IOException
      • RuntimeException
    • Error

异常的Methods(Exceptions Methods)

捕获异常(Catching Exceptions)

try/catch

多个catch块(Multiple catch Blocks)

try{    //Protected code}catch (ExceptionType1 e1){    //Catch block}catch (ExceptionType2 e2){    //Catch block}catch (ExceptionType3 e3){    //Catch block}

throws/throw 关键字

  • throws:丢掉已知异常而不处理(not handle a checked exception),放在方法签名的后面
  • throw:抛出异常
public class className{    public void deposit(double amount) throws RemoteException  //丢掉异常    {        // Method implementation        throw new RemoteException();  //抛出异常    }    public void withdraw(double amount) throws RemoteException, InsufficientFundsException  //丢掉多个异常不处理    {        // Method implementation    }    //Remainder of class definition}

finally 关键字

不论try块是否发生异常,finally块总是被执行。

try{    //Protected code}catch (ExceptionType1 e1){    //Catch block}catch (ExceptionType2 e2){    //Catch block}finally{    //The finally block always executes.}

申明自定的异常(Declaring your own Exception)

  • 所有的exception都是Throwable的孩子(All exceptions must be a child of Throwable)
  • 编译时可检查的异常扩展自Exception
  • 运行时异常扩展自RuntimeException

例如:

class MyException extends Exception{}

通用异常(Common Exceptions)

两类异常和错误(Exceptions and Errors)

  • JVM Exceptions:JVM抛出的异常,比如NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException
  • Programmatic exceptions:应用或API抛出的异常,比如IllegalArgumentException, IllegalStateException

0 1