Java学习日常(异常处理)

学习内容

Java 的异常处理方法;
  • 产生的原因有两点:
    1.编译时的错误;
    2.运行时的异常(不允许发生);
  • 处理方法:
    使用try catch;
  • 代码验证
public class Demo1 {
    public static void main(String[] args) {
        String str = "abc";
        str = null;
        fun1("abc", null);
    }

    public static int div(int m, int n) {
        int k = m / n;
        return k;
    }

    public static void fun1(String str, String subStr) {
        try {
            System.out.println("11111111");
            int i = 10 / 0;
            if (str.indexOf(subStr) >= 0) {
                System.out.println("存在子串");
            } else {
                System.out.println("不存在子串");
            }
            System.out.println("end");
        } catch (Exception ex) {
            System.out.println("程序出现错误");
            ex.printStackTrace();
            System.out.println("#"+ex.getMessage());
            }
  • 资源回收
    使用finally来实现资源回收
  • 代码验证
finally {
            // 一定会被执行的代码块
            System.out.println("finally");
        }
  • 自定义的创建一个异常对象
throw new Exception
  • 在方法定义的后面显式的声明方法是有异常的,调用该方法的程序是要显式的处理异常,后者也可以再次向上抛出,该不处理异常。
throws Exception
异常堆栈信息

1.异常类
2.异常提示信息:getMessage()
3.异常所在的代码位置:自下而上是异常出现的代码所在方法的调用顺序的先后。

学习总结

对于今天的一天的学习还算是很繁忙的,自习的时间回顾了前面所学的知识内容,时间对于现在的我而言是非常紧迫的,有可能是自己的学习方法的问题,总感觉时间不够用,东西学不完。

猜你喜欢

转载自blog.csdn.net/weixin_42707543/article/details/82227385
今日推荐