Day-14

1.         异常机制

1.1        概述

异常是Java中提供的一种识别及响应错误情况的一致性机制。有效地异常处理能使程序更加健壮、易于调试。

异常发生的原因有很多,比如

  1. 用户输入了非法数据
  2. 要打开的文件不存在
  3. 网络通信时连接中断
  4. JVM内存溢出
  5. 这些异常有的是因为用户错误引起,有的是程序错误引起的,还有其它一些是因为物理错误引起的。

1.2        之前常见的异常

空指标

下标越界

栈内存溢出

数据类型异常

1.3        继承体系

1.4        Error

                非编译异常

1. 概念

系统内部错误,这类错误由系统进行处理,程序本身无需捕获处理。 

比如:OOM(内存溢出错误)、VirtualMachineError(虚拟机错误)、StackOverflowError(堆栈溢出错误)等,一般发生这种情况,JVM会选择终止程序。

2. 示例

//堆栈溢出错误

public class TestError {

    public static void recursionMethod() {

        recursionMethod();// 无限递归下去

    }

    public static void main(String[] args) {

        recursionMethod();

    }

}

报错信息:

Exception in thread "main" java.lang.StackOverflowError

    at com.TestError.recursionMethod(TestError.java:5)

    at com.TestError.recursionMethod(TestError.java:5)

    at com.TestError.recursionMethod(TestError.java:5)

    at com.TestError.recursionMethod(TestError.java:5)

    at com.TestError.recursionMethod(TestError.java:5)

    at com.TestError.recursionMethod(TestError.java:5)

... ...

1.5        Exception

1.5.1        是什么

Exception是所有异常类的父类。分为非RuntimeException和RuntimeException

非RuntimeException 
指程序编译时需要捕获或处理的异常,如IOException、自定义异常等。属于checked异常。

RuntimeException 
指程序编译时不需要捕获或处理的异常,如:NullPointerException等。属于unchecked异常。一般是由程序员粗心导致的。如空指针异常、数组越界、类型转换异常等。 

1.5.2        常用方法

 异常发生的原因有很多,尤其是用户输入和要打开的资源不存在
 
 这些异常出错后,会导致程序生命周期终止执行,从错误代码开始,之后的代码都不会执行
  
 java中 有一个专门模拟异常的类,就是 Throwable , 所有异常都继承这个类

public class Exception_02 {
public static void main(String[] args) {
    

//    public static void main(String[] args) throws FileNotFoundException {
    //打开资源文件
        try {
            FileInputStream fis = new FileInputStream("D:/xxx");
            System.out.println(123);
        }catch (FileNotFoundException e) {
            // 打印错误的追踪栈帧,比较常用,适合程序员排错
            //e.printStackTrace();
            
            //获取错误信息,适合响应给用户
            String msg =e.getMessage();
            System.out.println(msg);
            
        }
        System.out.println(222);
    }

}

1.5.3        Try...catch

1.5.3.1        第一种

 

 

 

1.5.3.2        第二种

 

public class Exception_05 {

    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("");
        } catch (FileNotFoundException e) {
        System.out.println("找不到文件");
        }catch (NullPointerException e) {
            System.out.println("不能为null");
        }catch (Exception e){
            System.out.println("其他异常");
        }
    }

}
 

1.5.3.3        第三种

 

1.5.4        覆写

父类抛出的类,可以是对应的子类,不能是它的父类

 

1.5.5        Throws

并不会处理异常,只会提醒你,可以抛出,也可以try..catch处理掉

-------------------

public static void main(String[] args) throws FileNotFoundException {
        m1();
    }
    public static void m1() throws FileNotFoundException{
        m2();
    }
    public static void m2() throws FileNotFoundException{
        m3();
    }
    public static void m3() throws FileNotFoundException{
        m4();
    }
    public static void m4() throws FileNotFoundException{
        FileInputStream fis = new FileInputStream("xxx");    
        }
}

注意: 可以同时抛出多个异常,用逗号隔开,没有先后的顺序

1.5.6        Finally

1.5.6.1        使用

finally : 必须执行的语句块 比如 打开的资源,需要关闭

1 finally 不能单独出现,必须和try一起使用 或者和 try...catch...一起使用

2 finally语句块 只有一种不执行的情况,那就是关闭虚拟机 System.exit(0)

----------------

    public static void main(String[] args) {
        try {
            int a =0;
            int b= 3;
            //除数不能为0,否则会出错
            int c=b/a;
            System.out.println(c);
        } catch (Exception e) {
            e.printStackTrace();
            // 终止方法执行
            return;
            // System.exit(0);
        }finally{    
            // 但是finally会执行
            System.out.println("2222");
        }
        System.out.println("11111");
    }

 -----------

1.5.6.2        注意

-----------------

    public static void main(String[] args) {
        int result=m1();
        //11
        System.out.println(result);
    }
     public static int m1(){
         int i=10;
         try {
             //因为finally中有return,而且优先级是比较高的
             //所以在编译的时候 就把这里的return去掉了,只有i++
            return i++;
            //i++
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 11
            //        return i;
            System.out.println(i+"----------------");
        }
            return i;
     }
-------------

1.5.6.3        应用场景

package com;

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

public class Exception_09 {

    public static void main(String[] args) {
        //作用域提升
        FileInputStream fis=null;
        try {
            //打开资源
             fis = new FileInputStream("xxx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            try {
                //判断是否打开资源,如果打开 就关闭
                if(fis !=null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
}
        }
    }

}

------------------

1.5.7        Throw

异常源点

Throw new 异常类(错误信息);

参考自定义异常

1.5.8        自定义异常类

1.5.8.1        自定义

 

1.5.8.2        应用场景

 

 -------------------


    public static void login(String username,String password) throws Exception{
        if (username.equals("admin")) {
            if (password.equals("root")) {
                // TODO 登陆成功
                // return "登陆成功";
            }else {
                // TODO 密码不正确
                // return "密码不正确" ;
                throw new Exception("密码不正确");
            }
        }else{
            // TODO 用户名不正确
            // return "用户名不正确";
            throw new Exception("用户名不正确");
        }
    }
--------------

    public static void main(String[] args) throws Exception {
        Scanner scanner =new Scanner(System.in);
        System.out.println("请输入用户名和密码:");
        String username =scanner.next();
        String password = scanner.next();
        try {
            UserService.login(username,password);
            System.out.println("登陆成功");
        } catch (UserException e) {
            System.out.println(e.getMessage());
            }
    ---------

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值