Java异常的学习笔记

异常学习

1.异常的分类
异常分为编译时异常和运行时异常

package cn.itcast.day05.exception01;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
  Exception:属于编译时期异常-->代码一旦写上去,自动编译之后,直接报错
  RuntimeException:属于运行时区异常-->代码写上去,没有语法错误,不会报错,但是一运行就出错
 */
public class Demo02_Exception {
    public static void main(String[] args) {
        //编译时期异常
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Date parse = simpleDateFormat.parse("2017-01-01 01:00:00");

        //运行时期异常
        String s = null;
        System.out.println(s.length());

    }
}

2.异常出现的过程
在这里插入图片描述
3.异常的创建

package cn.itcast.day05.exception01;
/*
   异常的创建
      throw new 异常对象


      如果我们自己不创建异常对象,如果出现了异常,那么就是jvm自己创建,并抛出,如果没有处理 ,自己处理
      如果我们自己创建了异常对象,那么jvm就不自动创建了,自己创建出来,没有处理,还是jvm处理




 */
public class Demo04_Excetion {
    public static void main(String[] args) {
        int[] arr = new int[0];
        //System.out.println(arr.length);
        method(arr);
    }

    public static void method(int[] arr){

        if (arr.length==0){
          throw new ArrayIndexOutOfBoundsException("大哥,越界了!");
        }

        if (arr==null){
            throw new NullPointerException();
        }


        System.out.println("---------");
    }
}

4.异常的处理
方法一:throws抛出异常

package cn.itcast.day05.exception02;

import java.util.Objects;

/*
   异常处理方式1:throws  -->放在方法声明上

       throws一个异常对象,抛给main方法了,如果main方法没有手动throws给jvm,那么就是自动的
       如果我们在main方法的声明上手动throws,main就不会自动给jvm了


   throws处理异常,同时处理多个异常对象


   Objects
      public static <T> T requireNonNull(T obj) {
        if (obj == null)
      	throw new NullPointerException();
        return obj;
}


 */
public class Demo01_Exception {

    public static void main(String[] args)throws /*NullPointerException,ArrayIndexOutOfBoundsException*/Exception{
        int[] arr = null;
        method01(arr);

    }

    public static void method01(int[] arr) throws /*NullPointerException,ArrayIndexOutOfBoundsException*/ Exception {
        //Objects.requireNonNull(arr);

        if (arr.length==0){
            throw new ArrayIndexOutOfBoundsException("越界了");
        }

        if (arr==null){
            throw new NullPointerException();
        }

        System.out.println("我要执行了");
    }
}

方法二:try…catch

package cn.itcast.day05.exception02;

import java.io.FileNotFoundException;

/*
   异常处理方式2:
      try..catch

      格式:
         try{
            可能出现异常的代码
         }catch(异常对象 对象名){
            处理异常
         }

         注意:一般catch是直接将异常信息打印出来
             将异常信息打印到日志中

      注意通用的方式:
         不管是throws还是try..catch,我们最简单的方式就是直接处理Exception
 */
public class Demo02_Exception {
    public static void main(String[] args) {
        String s = "11.txt";
        try{
            String s1= null;
            System.out.println(s1.length());
            method01(s);
        }catch (Exception e){
            System.out.println(e);
        }

        System.out.println("game over");

    }

    public static void method01(String s) throws Exception {
        if (!s.equals("1.txt")){
            throw new FileNotFoundException();
        }

        System.out.println("我要执行了");
    }
}

try…catch处理多个异常

package cn.itcast.day05.exception02;

import java.io.FileNotFoundException;

/*
   try..catch,同时捕获多个异常

   try{
     可能出现的异常对象
   }catch(异常对象1 对象名){
      处理异常
   }catch(异常对象2 对象名){
      处理异常
   }

   注意:
    1.如果我们嫌弃多个catch麻烦,那么我们就直接一个catch Exception
    2.我们在使用多catch的情况下,要求先抓子类的,再抓父类,但是没必要,我们直接catch一个父类异常
 */
public class Demo03_Exception {
    public static void main(String[] args) {
        String s = "11.txt";
        try{
            method(s);
        }catch (FileNotFoundException e){
            System.out.println(e);
        }catch (ClassNotFoundException e){
            System.out.println(e);
        }
       /* try {
            method(s);
        } catch (Exception e) {
            System.out.println(e);
        }*/

        /*try {
            method(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/

       /* try {
            method(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }*/
    }

    public static void method(String s) throws FileNotFoundException, ClassNotFoundException {
        if (!s.equals("1.txt")) {
            throw new FileNotFoundException();
        }

        if (s.length() == 0) {
            throw new ClassNotFoundException();
        }
    }
}

idea中的快捷键:alt+enter或者ctrl+alt+t
5.finally的使用

package cn.itcast.day05.exception02;

import java.io.FileNotFoundException;

/*
  finally:都是跟try..catch一起使用

  格式:
     try{
       可能出现的异常
     }catch(异常对象 对象名){
       处理异常
     }finally{
       一定会执行的代码
     }

  使用场景:
     关闭资源
 */
public class Demo04_Exception {
    public static void main(String[] args) {
        String s = "11.txt";
        try {
            /*String s1 = null;
            System.out.println(s1.length());*/
            method(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            //System.exit(0);
            System.out.println("我就要执行,不管怎样,就要嘛");
        }
    }

    public static void method(String s) throws FileNotFoundException {
        if (!s.equals("1.txt")) {
            throw new FileNotFoundException();
        }
        System.out.println("我执行了");
    }

}

6.两种异常处理方式的区别
在这里插入图片描述
throws:直接往上抛出,自己不做具体处理,抛给调用者(不要一味的往上抛)
try…catch:不交给jvm了,我们自己处理(一般try…catch都是统一处理)
7.编译时期异常和运行时期异常的处理时机

package cn.itcast.day05.exception02;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/*
   编译时期异常和运行时期异常的处理时机
     运行时期异常:不用代码处理   ,证明你的代码写的有问题,自己改去吧

     编译时期异常:一般我们直接throws或者try..catch

 */
public class Demo06_Exception {
    public static void main(String[] args) throws ParseException, FileNotFoundException {
        int[] arr = new int[10];
        //System.out.println(arr[10]);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.parse("2017-01-01 01:01:00");

        FileInputStream fileInputStream = new FileInputStream("D:\\1.txt");
    }
}

8.获取异常信息的三种方式

package cn.itcast.day05.exception02;

import java.io.FileNotFoundException;
/*
   - public String getMessage():获取异常的描述信息,原因(提示给用户的时候,就提示错误原因。
   - public String toString():获取异常的类型和异常描述信息(不用)。
   - public void printStackTrace():打印异常的跟踪栈信息并输出到控制台。-->常用

 */
public class Demo07_Exception {
    public static void main(String[] args) {
       String s = "11.txt";

        try {
            method02(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static void method02(String s) throws FileNotFoundException {
        if (!s.equals("1.txt")){
            throw new FileNotFoundException("文件找不到");
        }
    }
}

9.异常在子父类继承关系中的注意事项

package cn.itcast.day05.exception02;

import java.io.FileNotFoundException;
import java.io.IOException;

/*
   异常在子父类继承关系的情况下的注意事项(方法重写方面)


   1.父类中的方法,抛了异常,那么子类重写之后用抛异常吗

      可抛可不抛   但是如果抛了,要是父类方法抛的异常的子类或者同类

   2.如果父类中的方法,没有抛异常,子类重写之后用抛吗?

     不用抛

 */
public class Demo08_Exception {
}

class Fu{
    public void method(){
        System.out.println("我是父类中的method");
    }
}

class Zi extends Fu{
    public void method()/*throws FileNotFoundException*/{
        System.out.println("我是父类中的method");
    }
}

10.自定义异常
定义异常

package cn.itcast.day05.exception03;

public class RegisterException extends RuntimeException{//这个是自定义运行时的异常,如果自定义编译时的异常,则extends Exception
    public RegisterException() {
    }

    public RegisterException(String message) {
        super(message);
    }
}

使用自定义异常

package cn.itcast.day05.exception03;

import java.util.Scanner;

/*
   模拟注册功能

   1.定义数组,存储几个用户名
   2.键盘录入一个名字,判断在不在数组中
   3.如果在,直接抛出一个注册异常
   4.否则,注册成功
 */
public class Test {
    public static void main(String[] args) {
        String[] name = {"张无忌","曹云金","孟鹤堂","柳岩"};
        method(name);
    }

    private static void method(String[] name){
        Scanner sc = new Scanner(System.in);
        System.out.println("请你输入要注册的名字:");
        String username = sc.next();

        for (int i = 0; i < name.length; i++) {
            if (username.equals(name[i])){
                throw new RegisterException("用户名已经存在!");
            }
        }
        System.out.println("注册成功");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值