java进阶基础---2.1---异常Exception及执行

小梁同学 の

Java学习旅途

你好! 这是小梁同学使用 博客 所记录的文章笔记,作为一个初学者的从基础到未来的记录,如果你想和我一起在Java学习路程上坚持下去,欢迎你的关注与指正。

新的将来

万丈高楼平地起,未来只能靠自己
从无到有,从零到一,学习路上没有尽头
每日一文,每日一记,跟着软件向前努力
加油!!!!!

详解代码均在以下标题后的链接中

以下所有有关代码,都是个人在上完课后自己重新敲代码之后所做笔记后上传,并非原搬直接上传,谢谢理解

二.JAVA进阶

一.异常Exception

1.基本概念

异常:在Java中异常处理机制能让程序在异常发生时按照预先设定好的处理逻辑去有针对性的解决问题

java.lang.Throwable类是Java中所有错误异常的超类

**直接子类:**Error类和Exception类

2.主要分类

1.异常:

java.lang.Exception类是所有异常的超类

名称说明
RuntimeException运行时异常(非检测性异常)
IOExceptionIO异常(检测性异常)
2.RuntimeException类的主要子类
异常类型说明
ArithmeticException算数异常
ArrayIndexOutofBoundsException数组下标越界异常
NullPointerException空指针异常
ClassCastException类型转换异常
NumberFormatException数字格式异常
//ArithmeticException算数异常
	int a=20;
	int b=0;
	System.out.println(a/b);
=====================
    Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.liang.Exception01.Test.main(Test.java:11)
        
//ArrayIndexOutOfBoundsException数组下标越界异常
	int[] arr = new int[9];
	int pos = 9;
	System.out.println(arr[pos]);
=====================
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
	at com.liang.Exception01.Test.main(Test.java:11)
        
//NullPointerException空指针异常
	String c = null;
	System.out.println(c.length());
=====================
    Exception in thread "main" java.lang.NullPointerException
	at com.liang.Exception01.Test.main(Test.java:10)
    
//ClassCastException类型转换异常
	Exception e = new Exception();
	IOException i = (IOException) e;
=====================
    Exception in thread "main" java.lang.ClassCastException: java.lang.Exception cannot be cast to java.io.IOException
	at com.liang.Exception01.Test.main(Test.java:12)
        
//NumberFormatException数字格式异常
	String s = "159+";
	System.out.println(Integer.parseInt(s));
=====================
    Exception in thread "main" java.lang.NumberFormatException: For input string: "159+"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.liang.Exception01.Test.main(Test.java:12)
3.运行时异常处理

​ 对于大多数的运行时异常/非检测性异常都可以采用if()条件判断的方式避免发生。

//ArithmeticException算数异常解决
	int a=20;
	int b=0;
	if(b != 0){
        System.out.println(a/b);
    }
	System.out.println("算数异常");
=====================
    算数异常
        
//ArrayIndexOutOfBoundsException数组下标越界异常解决
	int[] arr = new int[9];
	int pos = 9;
	if(pos>=0 && pos<9){
        System.out.println(arr[pos]);
    }
	System.out.println("数组下标越界异常");
=====================
    数组下标越界异常
        
//NullPointerException空指针异常解决
	String c = null;
	if(c != null){
    	System.out.println(c.length());
	}
	System.out.println("空指针异常");
=====================
    空指针异常
    
//ClassCastException类型转换异常解决
	Exception e = new Exception();
	if(e.instanceof IOException){
        IOException i = (IOException) e;
    }
	System.out.println("类型转换异常");
=====================
    类型转换异常
        
//NumberFormatException数字格式异常解决
	String s = "159+";
	if(s.matches("\\d+")){
        System.out.println(Integer.parseInt(s));
    }
	System.out.println("数字格式异常");
=====================
    数字格式异常

3.异常捕获

//格式
try{
    编写可能出现异常的语句;
}catch(异常类型  变量名){
    编写针对该异常的处理语句;
}finally{
    编写无论是否发生异常都会执行的语句块;
}

4.异常执行流程

       //创建一个文件时,FileOutputStream会显示错误
       FileOutputStream fos = new FileOutputStream("./a.txt");
====================
    Error:(14, 32) java: 未报告的异常错误java.io.FileNotFoundException; 必须对其进行捕获或声明以便抛出
        
        //创建文件时抛出异常进行捕获,能够正常创建
        try {
              FileOutputStream fos = new FileOutputStream("./a.txt");
        } catch (FileNotFoundException e) {
              e.printStackTrace();
        }
===================

    	//读文件时也要抛出异常后进行读取
        try {
            FileInputStream fis = new FileInputStream("./b.txt");
        } catch (FileNotFoundException e) {
            System.out.println("b.txt没有被找到");
        }
===================
    b.txt没有被找到
//当需要catch()多种不同类型的的时候,小的类型需要放在大的类型的上面
	try {
            FileInputStream fis = new FileInputStream("./b.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
====================
    java.io.FileNotFoundException: .\b.txt (系统找不到指定的文件。)

5.手动抛异常

​ 在某些特殊的情况下,对于无法直接捕获的或不方便捕获异常时,就可以选择将异常转移给方法的调用者,这种形式叫做异常的抛出。

//1.异常的抛出
public class Test01 {
    public static void main(String[] args) {
        try {
            Test01.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //异常抛出时,会将异常抛给方法的调用者
    //返回值类型  方法名(形参列表)throws 异常类型1,异常类型2 
    public static void show() throws FileNotFoundException ,IOException{
        FileInputStream fis = new FileInputStream("./b.txt");
        fis.close();
    }
}
//2.父类方法抛出异常
//当父类中有异常时,子类重写父类方法时对于异常的处理
public class Test02 {
    public void show() throws IOException {
        System.out.println("我是Test02中的show方法");
    }
}

public class SubTest02 extends Test02{
    @Override   //子类可以抛出与父类相同的异常
    public void show() throws IOException {
        super.show();
    }
    @Override    //子类可以抛出比父类小的异常
    public void show() throws FileNotFoundException {
        System.out.println("我是子类的show方法");
    }

    @Override	//子类不可以抛出比父类更大的异常
    public void show() throws Exception { 
        System.out.println("我是子类的show方法");
    }
}

6.自定义异常

public class Student {
    private String name;
    private int age;
    
    public Student(){
    }

    public Student(String name, int age) throws AgeException {
        setName(name);
        setAge(age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws AgeException {
        this.age = age;
        if(age<0 || age>150){
            throw new AgeException("年龄不合理!");
        }else{
            this.age = age;
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class AgeException extends Exception{
    //继承Exception
    public AgeException() {
    }

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

public class Test03 {
    public static void main(String[] args) {
        Student stu =null;

        try {
            stu = new Student("Mark", 160);
        } catch (AgeException e) {
            e.printStackTrace();
        }
        System.out.println(stu);
    }
}
==================
    null
	com.liang.Exception01.AgeException: 年龄不合理!
	at com.liang.Exception01.Student.setAge(Student.java:34)
	at com.liang.Exception01.Student.<init>(Student.java:16)
	at com.liang.Exception01.Test03.main(Test03.java:12)

7.final、finally、finalize

方法名说明
final修饰的变量不可修改、方法不可重写、类不可被继承
finally异常处理机制中的一个关键字
finalize垃圾回收器被执行之前被调用的方法
//1.final
public class Test04 {
    public final static String name="Jack";
    public static void main(String[] args) {
        //Cannot assign a value to final variable 'name'
        //name不可被修改
        name = "Make";
    }
}

//2.finalize
public class Test04 {
    public static void main(String[] args) {
        Test04 test04 = new Test04();
        //将对象设置为空值,会调用finalize方法,若未设置,则不会调用
        test04=null;
        //调用垃圾回收器
        System.gc();
    }
    @Override
    protected void finalize() throws Throwable {
        System.out.println("调用finalize方法");
    }
}

java入门基础—1.8----上一章节: 跳转

java进阶基础—2.2----下一章节: 跳转

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值