JavaSE: 异常的抛出

基本概念:ide

  在某些特殊状况下,有些异常不能处理,或者不便于处理时,就能够 将 该异常 转移给对象

  该方法的 调用者, 这种方法 就叫 异常的抛出。it

  当方法执行时出现异常,则底层生成一个 异常类对象 抛出,此时异常代码后续的代码 就再也不执行。io

 

语法格式:class

  访问权限 返回值类型 方法名称(形参列表) throws 异常类型1, 异常类型2,... { 方法体;}test

  如:权限

    public void show() throws IOException {语法

    }方法

 

示例:经验

 

public class ExceptionThrowsTest {

 

  public static void show throws IOException(){

    FileInputStream fis = new FileInputStream("d:/a.txt"); // 发生异常

    printIn ("我想看看你抛出异常后是否继续向下执行"); // 没有执行

    fis.close();

  }

  // 不建议在main方法中抛出异常, 由于 JVM的负担已经很重了

  public static void main(String[] args) /* throws IOException */ {

    try {

      show();

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

 

异常抛出的补充

示例:

 

// 父类

public class ExceptionMerhod {

  

  public void show() throws IOException {

 

  }

}

 

// 子类

public class SubExceptionMethod extends ExceptionMethod {

 

  @Override

  // public void show() throws IOException { }  //  子类重写的方法能够抛出和父类中方法同样的Exception

  // public void show() throws FileNotFoundException { }  //  子类重写的方法能够抛出更小的Exception

  // public void show() {}  //  子类能够 不抛出异常

  // public void show() throws ClassNotLoadedException {}  //  不能够抛出平级不同的异常 

  // public void show() throws Exception {}  //  不能够抛出更大的异常  (”孩子不能比爹更坏“)

}

 

经验:

  1.  若父类中被重写的方法没有抛出异常时,则子类中重写的方法只能进行异常的捕获处理。 (由于子类不能抛出更大的异常)

  2.  若一个方法内部又以递进方式分别调用了几个好几个其余方法,则建议这些方法内可使用抛出的方法处理到外面一层进行捕获方式处理。

 

经验2 - 示例:

public class ExceptionThrowsTest {

 

  public static void show throws IOException(){

    FileInputStream fis = new FileInputStream("d:/a.txt"); // 发生异常

    printIn ("我想看看你抛出异常后是否继续向下执行"); // 没有执行

    fis.close();

  }

 

  public static void test1() throws IOException { //  抛到外面一层 - show()

    show();

  }

 

  public static void test2() throws IOException { //  抛到外面一层 - test1()

    test1();

  }

 

  public static void test3() throws IOException { //  抛到外面一层 - test2()

    test2();

  }

 

  main(){

    try{

      test3();

    }

    catch(IOException e){

      e.printStackTrace();

    }

  }

}

相关文章
相关标签/搜索