栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

day050:try...catch...常见问题、throwable的成员方法、自定义异常

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

day050:try...catch...常见问题、throwable的成员方法、自定义异常

接上节:​​​​​​day049:异常、throws声明异常、throw抛出异常、异常的处理方式_ZQyyds:)的博客-CSDN博客 一、try...catch...常见问题 1.常见问题:
  • 当try中没有遇到异常,会怎么执行?
    • 会把try中的代码全部执行,不会执行catch中的代码
  • 当try中遇到异常,会怎么执行?
    • try中遇到异常后,直接运行catch中的代码
  • 如果异常没有被捕获,程序会如何运行?
    • 异常没有被捕获时,try...catch...就相当于没有写,由JVM虚拟机默认处理异常
  • 同时出现多个异常时,会怎么处理?
    • 出现多个异常,可以写多个catch;如果多个异常之间存在子父类关系,则父类一定要写在下面(Exception范围最大,其余的空指针异常、数组索引越界异常等都为子类)

二、throwable的成员方法 1.异常里常见的成员方法:
  • public String getMessage()        返回此异常的详细信息字符串
  • public String toString()        返回此异常抛出的简短描述
  • public void printStackTrace()       把异常的错误信息输出在控制台上

代码示例:

第一个:getMessage:
  

public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3, 4, 5, 6};
            System.out.println(arr[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            String message = e.getMessage();
            System.out.println(message);
            //输出:Index 10 out of bounds for length 6
        }
    }
第二个:toString

public class exceDemo_04 {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3, 4, 5, 6};
            System.out.println(arr[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            String s = e.toString();
            System.out.println(s);
            //输出:java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
        }
    }
}
第三个:printStackTrace


public class exceDemo_04 {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3, 4, 5, 6};
            System.out.println(arr[10]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
            //输出:java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
            //	at com.itheima.exception.exceDemo_04.main(exceDemo_04.java:11)
        }
    }
}

三、自定义异常 1.自定义异常的目的:让异常信息更加清晰,见名知意。 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924335.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号