第八章 Java异常处理学习

1.异常的层次

        java.lang.Throwable是异常和错误的最顶级;Throwable两个分支:Exception和Error:Exception是程序正常运行过程中可遇到到的意外情况,并且应该被捕获,进行相应的处理,是所有异常类的父类;Error表示致命的错误,他不是异常,是错误。

2.异常的介绍

        程序运行过程中可能发生的不正常的事件;会中断正在运行的程序。异常处理提高健壮性。

3.概述和体系结构

        在Java语言中,将程序执行中发生不正常情况称为异常(语法错误和逻辑错误不是异常)。
        Java程序执行过程中回发生两类异常:Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等。StackOverflowErrorr和OOM一般不编写针对性的代码进行处理。

public class ErrorTest {
	public static void main(String[] args) {
		// 1.栈溢出:java.lang.StackOverflowError
		// main(args);
		// 2.堆溢出:java.lang.OutOfMemoryError
		Integer[] arr = new Integer[1024 * 1024 * 1024];
	}
}

        Exception: 因编程错误或偶然的外在因素导致的一般性问题,可使用针对性的代码进行处理。如:空指针访问;试图读取不存在的文件;网络连接中断等。两种解决方法:一是遇到错误就终止程序的运行;二是编写程序时,考虑错误的检测、错误消息的提示,以及错误的处理
        捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。比如:除数为0,数组下标越界等。分为编译时异常和运行时异常

3.1.运行时异常

        编译器不要求强制处置的异常。一般是指编程时逻辑错误,是程序员应积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常;对于这类异常,可不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。

3.2.编译时异常

        编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。如果程序不处理,可能会带来意想不到的结果。

3.3.常见的异常

异常描述
ArithmeticException一般是除以0会出现如下异常
ArrayIndexOutOfBoundsException一般是非法索引访问数组出现的异常
IndexOutOfBoundsException索引(数组、字符串、向量)超出范围
IllegalArgumentException向方法抛出不正确或者不合法的参数
NullPointerException《最常⻅的异常》 访问对象的值是null
ClassNotFoundException当应用程序尝试通过其字符串名称加载到类中时抛出
//ArrayIndexOutOfBoundsException
public class IndexOutExp {
    public static void main(String[] args) {
        String friends[] = { "lisa", "bily", "kessy" };
        for (int i = 0; i < 5; i++) {
            System.out.println(friends[i]); // friends[4]?
        }
            System.out.println("\nthis is the end");
    }
}
// 输出
程序IndexOutExp.java编译正确,运行结果:java IndexOutExp
lisa
bily
kessy
java.lang.ArrayIndexOutOfBoundsException
at Test7_1.main(Test7_1.java:5)
Exception in thread "main"

//NullPointerException
public class NullRef {
    int i = 1;
    public static void main(String[] args) {
        NullRef t = new NullRef();
        t = null;
        System.out.println(t.i);
    }
}
// 输出
程序NullRef.java编译正确,运行结果:java NullRef
java.lang.NullPointerException
at NullRef.main(NullRef.java:6)
Exception in thread "main"

//ArithmeticException
public class DivideZero {
    int x;
    public static void main(String[] args) {
        int y;
        DivideZero c=new DivideZero();
        y=3/c.x;
        System.out.println("program ends ok!");
    }
}
// 输出
程序DivideZero.java编译正确,运行结果:java DivideZero
java.lang.ArithmeticException: / by zero
at DivideZero.main(DivideZero.java:6)
Exception in thread "main"

//ClassCastException
public class Order {
    public static void main(String[] args) {
        Object obj = new Date();
        Order order;
        order = (Order) obj;
        System.out.println(order);
    }
}
// 输出
程序Person.java编译正确,运行结果:java Person
java.lang. java.lang.ClassCastException
at Person.main(Person.java:5)
Exception in thread "main"

 4.异常处理机制

        Java的异常处理是通过5个关键字来实现的:trycatchfinallythrowthrows

        编写程序时,经常在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。过多的if-else分支会导致程序的代码加长、臃肿,可读性差。因此采用异常处理机制。
        Java异常:处理Java采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。

4.1.异常处理方式

        方式一:try-catch-finally
        方式二:throws + 异常类型

        Java提供的是异常处理的抓抛模型;Java程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常
        异常对象的生成:由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例对象并抛出——自动抛出;由开发人员手动创建:Exception exception = new ClassCastException();——创
建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样。
        如果一个方法内抛出异常,该异常对象会被抛给调用者方法中处理。如果异常没有在调用者方法中处理,它继续被抛给这个调用方法的上层方法。这个过程将一直继续下去,直到异常被处理。这一过程称为捕获(catch)异常。

if(一切正常){
    业务代码
}else{
    // 错误代码
}

// 用try ... catch改写
try{
    //业务代码
}catch(Exception e){
    // 错误代码
}

// 计算两个数相除
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    for (int i = 0; i < 3; i++) {
        System.out.println("请输入被除数:");
        int x = sc.nextInt();
        System.out.println("请输入除数:");
        int y = sc.nextInt();
        System.out.println("商是:" + (x/y) + ",余数是:" + (x%y));
    }
}

// 若运行 1/0 ,程序会报错。并且循环终止,退出程序
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    for (int i = 0; i < 3; i++) {
        try {
            System.out.println("请输入被除数:");
            int x = sc.nextInt();
            System.out.println("请输入除数:");
            int y = sc.nextInt();
            System.out.println("商是:" + (x/y) + ",余数是:" + (x%y));
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("有误!");
            continue;
        }
    }
}

     catch中异常类型无子父类关系,谁声明在上面和下面无不影响,但catch异常满足子父类关系,则要求子类一定声明在父类的上面,否则不会执行到子异常。常用的异常处理方式①String getMeeage():②printStackTrace();在try结构中声明的变量,再出了try结构以后,就不能在被调用;try-catch-finally结构可以嵌套。

方法描述
getMessage()返回发生异常的详细信息
toString()把异常信息用字符串的形式返回
printStackTrace()打印异常轨迹到栈层次里面

        使用try-catch-finally处理编译时异常,程序在编译时就不再报错,但是运行是仍可能报错。相当于使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现;开发中,由于运行时异常比较常见,所以通常就不针对运行时异常编写try-catch-finally。

public class ExceotionTest1 {
	@Test
	public void test4() {
		String str = "123";
		str = "abc";
		try {
			int num = Integer.parseInt(str);
		} catch (NullPointerException e) {
			System.out.println("空指针异常");
		} catch (NumberFormatException e) {
			// System.out.println("出现数值类型转换错误");
			// String getMeeage():
			// System.out.println(e.getMessage());
			// printStackTrace();
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("出现异常");
		}
	}
}

         try ... catch块捕获:如果没有try .. catch 块,若出现了异常,异常就会抛给JRE,这个过程叫抛异常。运行时环境终止,Java程序退出。
        如果有try ... catch块,若出现异常,首先会把异常对象抛给运行时环境,运行时环境去寻找对应的catch块去捕获异常。若运行时环境找不到一个处理该异常的catch块,则继续抛给运行时环境,运行时环境终止,Java程序退出。
        多重捕获:一个try代码块后面跟随多个catch块的情况,叫做多重捕获。

try{
    // 业务代码
}catch(异常类型1 异常变量名1){
    // 捕获快1的代码
}catch(异常类型2 异常变量名2){
    //捕获快2的代码
}catch(异常类型3 异常变量名3){
    //捕获快3的代码
}

// 例子
public static void main(String[] args) {
    try {
        int i = 1/0;
    }catch (ArithmeticException ae) {
        System.out.println("ArithmeticException捕获");
    }catch (RuntimeException re) {
        System.out.println("RuntimeException捕获");
    }catch (Exception e) {
        System.out.println("Exception捕获");
    }
}
// 输出:ArithmeticException捕获"

        注意:在安排catch语句的顺序时,首先应该捕获最特殊的异常,  然后再逐渐一般化,即先子类后父类。

4.2.try-catch-finally异常处理

        try:捕获异常的第一步,选定捕获异常的范围,将可能出现异常的代码放在try语句块中。
        catch (Exceptiontype e):在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。
        如果明确知道产生何种异常,可用该异常类作为catch的参数;也可用其父类作为catch的参数。如 : 可用RuntimeException或Exception替换ArithmeticException类作,但不能用ArithmeticException类无关异常,如NullPointerException,将不会执行。
        捕获异常相关信息:与其它对象一样,可访问一个异常对象的成员变量或调用它的方法。getMessage() 获取异常信息,返回字符串;printStackTrace() 获取异常类名和异常信息,以及异常出现在程序中的位置。
        finally:捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分前,能够对程序的状态作统一的管理;不论在try代码块中是否发生了异常事件,catch语句是否执行,catch语句是否有异常,catch语句中是否有return,finally块中的语句都会被执行;finally语句和catch语句是任选的。finally块中语句不执行的唯一情况:异常处理代码中执行System.exit(1)退出Java虚拟机 。作用:try里面打开系统资源,然后在finally里面释放。
       try后必须有catch块或finally块,不能独立存在。

// 语法
try{
}catch(Exception e){
}finally{
}
// 或者
try{
}finally{
}

import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception01 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		try {
			System.out.print("请输入被除数:");
			int num1 = input.nextInt();
			System.out.print("请输入除数:");
			int num2 = input.nextInt();
			System.out.println("商为:" + String.format("%d  / %d = %d", num1, num2, num1 / num2));
			input.close();// 关闭Scanner输入
		} catch (InputMismatchException e) {// 输入类型不匹配
			// e.printStackTrace();
			System.err.println("请输入整数");
		} catch (ArithmeticException e) {// 除数为0
			// e.printStackTrace();
			System.err.println("除数不能为0");
		} catch (Exception e) {
			// e.printStackTrace();
			System.err.println("程序开小差,稍等一会");
		} finally {
			System.out.println("无论如何finally都会指向");
		}
		System.out.println("程序结束");
	}
}

        try、catch和finally执行顺序,分以下几种情况:
        1.没有return:
如果try中无异常,则执行顺序:try —> finally;若果try中有异常,则执行顺序:try —>catch —> finally

public static void main(String[] args) {
    int[] a = new int[2];
    try {
        System.out.println("try块执行!");
        System.out.println("a【3】 :" + a[3]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("catch块执行!");
        System.out.println("数组下标越界");
    }finally {
        a[0] = 6;
        System.out.println("finally块执行!");
        System.out.println("a[0]:" + a[0]);
    }
}

        有return

// 返回值时基本类型
// 基本类型有一个暂存操作:在执行finally之前会把i值暂存,然后再去执行finally,
// 执行完毕之后,在返回暂存的值。
public static int testEx() {
    int i = 0;
    try {
        i = 1;
        System.out.println("try块执行!");
        return i;
    } catch (Exception e) {
        System.out.println("catch块执行!");
    }finally {
        i = 2;
        System.out.println("finally块执行");
    }
        return i;
}
public static void main(String[] args) {
    int i = testEx();
    System.out.println(i);
}

// 输出
try块执行!
finally块执行
1

// 返回值对象类型
public static StringBuffer testEx() {
    StringBuffer sb = new StringBuffer("aa");
    try {
        sb.append("bb");
        System.out.println("try块执行");
        return sb;
    } catch (Exception e) {
        System.out.println("catch块执行");
    }finally {
        sb.append("cc");
        System.out.println("finally块执行");
    }
    return sb;
}
public static void main(String[] args) {
    StringBuffer s = testEx();
    System.out.println(s);
}

// 输出
try块执行
finally块执行
aabbcc

         java7自动关闭资源的try语句

public static void main(String[] args) {
    FileInputStream fis = null;
    try {
        // 开启系统资源
        fis = new FileInputStream("a.txt");
        fis.read();
    } catch (IOException e) {
    e.printStackTrace();
    }finally {
        try {
            fis.close();//释放系统资源
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

        java7后可以使用自动关闭资源的try语句,try关键字后面加一对圆括号,在圆括号里面声明、初始化、关闭一个或多个资源。

public static void main(String[] args) {
    try(FileInputStream fis = new FileInputStream("a.txt")) {
        fis.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.3.不捕获异常情况

        RuntimeException类或是它的子类特点:即使没有使用try和catch捕获,Java自己也能捕获,并且编译通过( 但运行时会发生异常使得程序运行终止 )。
        如果抛出的异常是IOException等类型的非运行时异常,则必须捕获,否则编译错误

// 例1
import java.io.*;
public class IOExp {
    public static void main(String[] args) {
        FileInputStream in = new FileInputStream("atguigushk.txt");
        int b;
        b = in.read();
        while (b != -1) {
            System.out.print((char) b);
            b = in.read();
        }
        in.close();
    }
}

// 例2
import java.io.*;
public class IOExp {
    public static void main(String[] args) {
        try {
            FileInputStream in = new FileInputStream("atguigushk.txt");
            int b;
            b = in.read();
            while (b != -1) {
                System.out.print((char) b);
                b = in.read();
            }
            in.close();
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            System.out.println(" It’s ok!");
        }
    }
}

4.4.throws声明抛出异常处理机制

        如果一个方法执行时可能生成某种异常,但不能确定如何处理这种异常,此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。
        在方法声明中用throws语句可以声明抛出异常的列表,throws后的异常类型可是方法中产生的异常类型或它的父类。
        throws + 异常类型:写在方法的声明处,指明此方法执行时,可能抛出的异常类型。一旦方法执行并出现异常,并生成一个异常类对象,此对象满足throws后异常类型时,就会被抛出。
        try-catch-finally:真正的将异常给处理掉;throws:将异常抛给方法的调用者,并没有真正的将异常处理掉。

public class ExceptonTest2 {
	public static void main(String[] args) {
		try {
			method2();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void method2() throws IOException {
		method1();
	}

	public static void method1() throws FileNotFoundException, IOException {
		File file = new File("hello.txt");
		FileInputStream fileInputStream = new FileInputStream(file);
		int data = fileInputStream.read();
		while (data != -1) {
			System.out.println((char) data);
			data = fileInputStream.read();
		}
		fileInputStream.close();
	}
}

// 在方法名上抛异常
public static void main(String[] args) throws FileNotFoundException,ClassNotFoundException {
    new FileInputStream("f1le.txt");
    Class.forName("oracle.jdbc.Driver");
}

// 在方法内部抛异常
public void testException() {
    if ( 网络异常 ) {
        throw new ArithmeticException();
    }
}

       执行的方法a中,先后又调用另外的方法,这几个方法是递进关系执行的,建议这几个方法使用throws的方式进行处理,而执行的方法a可考虑使用try-catch-finally方式进行处理。
        声明异常:Java语言中通过throws声明某个方法可能抛出的各种异常;可同时声明多个异常,由逗号隔开。抛出异常:除了系统自动抛出异常外,有些问题需要程序员自行抛出异常。

public class Person {
	private int age;
	public void setAge(int age) throws Exception {
    // throws声明一个异常用在方法上面
		if (age > 0 && age < 130) {
			this.age = age;
		} else {
			throw new Exception("年龄不合法");// throw手动抛出一个异常
		}
	}
	public int getAge() {
		return age;
	}	
}

// 测试
public class TestPerson {
	public static void main(String[] args) {
		Person person = new Person();
		try {
			person.setAge(-18);
			System.out.println("age:" + person.getAge());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("程序结束");
	}
}

4.5.重写方法抛出异常的原则

        重写方法不能抛出比被重写方法范围更大的异常类型。在多态的情况下,对methodA()方法的调用-异常的捕获按父类声明的异常处理。
        方法重写规则:子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型。

public class OverrrideTest {
	public static void main(String[] args) {
		OverrrideTest test = new OverrrideTest();
		test.display(new SubClass());
	}

	public void display(SuperClass s) {
		try {
			s.method();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class SuperClass {
	public void method() throws IOException {

	}
}

class SubClass extends SuperClass {
	public void method() throws FileNotFoundException {

	}
}

4.6.手动抛出异常

        Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要使用人工创建并抛出。
        首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
        可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
        throw new String("want to throw");

5.用户自定义异常类

        一般用户自定义异常类都是RuntimeException子类;自定义异常类通常需要编写几个重载的构造器;自定义异常需要提供serialVersionUID;自定义的异常通过throw抛出;自定义异常最重要的是异常类的名字,当异常出现时,可根据名字判断异常类型。
        如何定义异常类:继承于异常结构:RuntimeException(运行时异常)、Exception;提供全局常量:serialVersionUID;提供重载的构造器。

public class MyException extends Exception {
	static final long serialVersionUID = -7034897190745766939L;
	public MyException(){
		
	}
	public MyException(String msg){
		super(msg);
	}
}
public class StudentTest {
	public static void main(String[] args) {
		Student student = new Student();
		try {
			student.tegist(-1001);
		} catch (MyException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}
class Student {
	private int id;
	public void tegist(int id) throws MyException {
		if (id > 0) {
			this.id = id;
		} else {
			// System.out.println("您输入的数据是非法的");
			// 手动抛出异常对象
			// throw new RuntimeException("您输入的数据是非法的");
			throw new MyException("不能输入负数");
		}
	}
	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
}

        用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。

class MyException extends Exception {
    static final long serialVersionUID = 13465653435L;
    private int idnumber;
    public MyException(String message, int id) {
        super(message);
        this.idnumber = id;
    }
    public int getId() {
        return idnumber;
    }
}

public class MyExpTest {
    public void regist(int num) throws MyException {
        if (num < 0)
            throw new MyException("人数为负值,不合理", 3);
        else
            System.out.println("登记人数" + num);
        }
        public void manager() {
            try {
                regist(100);
            } catch (MyException e) {
                System.out.print("登记失败,出错种类" + e.getId());
            }
            System.out.print("本次登记操作结束");
        }
    public static void main(String args[]) {
        MyExpTest t = new MyExpTest();
        t.manager();
    }
}

5.1.自定义异常练习

         当JDK 中的异常类型不能满足程序的需要时,可自定义异常类。自定义异常的步骤:1.自定义异常类(继承Exception或者RuntimeExcpotion);2.编写构造方法,继承父类的实现;3.实例化自定义异常;4使用throw抛出。

// 自定义异常
public class MyException extends Exception {
	private static final long serialVersionUID = 1L;
	public MyException() {
		super();
	}
	public MyException(String mssage) {
		super(mssage);
	}
}

public class Person {
	private String sex;
	public String getSex() {
		return sex;
	}
	// 自定义异常
	public void setSex(String sex) throws MyException {// 抛出的是我们自己定义的异常
		if (sex.equals("男") || sex.equals("女")) {
			this.sex = sex;
		}
		throw new MyException("性别错误");
	}
}

// 测试类
public class TestPerson {
	public static void main(String[] args) {
		Person person = new Person();
		try {
			person.setSex("man");
			System.out.println("sex:" + person.getSex());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("程序结束");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值