菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
178
0

JavaSE: 异常的抛出

原创
05/13 14:22
阅读数 20218

基本概念:

  在某些特殊情况下,有些异常不能处理,或者不便于处理时,就可以 将 该异常 转移给

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

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

 

语法格式:

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

  如:

    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.  若父类中被重写的方法没有抛出异常时,则子类中重写的方法只能进行异常的捕获处理。 (因为子类不能抛出更大的异常)

发表评论

0/200
178 点赞
0 评论
收藏