异常处理

异常处理基础

2021-07-06 386 2

简介 异常体系结构介绍、 try-cacth-finally、throws、throw关键字的使用



1. 异常概述与异常体系结构

    在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如: 客户输入数据的格式,读取文件是否存在, 网络是否始终保持通畅等等。

    异常:在Java语言中, 将程序执行中发生的不正常情况称为“异常” 。(开发过程中的语法错误和逻辑错误不是异常)

    Java程序在执行过程中所发生的异常事件可分为两类:

    Error: Java虚拟机无法解决的严重问题,名字为 XxxYyyZzz...Error。 如: JVM系统内部错误、 资源耗尽等严重情况。 比如: StackOverflowError和OutOfMemoryError(OOM)。 一般不编写针对性的代码进行处理,需要修改代码处理Error

    Exception: 其它因编程错误或偶然的外在因素导致的一般性问题, 可以使用针对性的代码进行处理,名字为 XxxYyyZzz...Exception。 例如:空指针访问、试图读取不存在的文件、网络连接中断、数组越界异常

//ErrorTest.java
package com.ylaihui.exception;

public class ErrorTest {
    	public static void main(String[] args) {
    		// 递归调用 没有终止导致的栈溢出 StackOverflowError
//		main(args);
		
    		// OutOfMemoryError  OOM 资源耗尽
//		Integer[] array = new Integer[1024000000*102400*102400];
	}
}

2. 异常如何解决

upfile


对于这些错误, 一般有两种解决方法:一是遇到错误就终止程序的运行。 另一种方法是由程序员在编写程序时, 就考虑到错误的检测、 错误消息的提示, 以及错误的处理。

捕获错误最理想的是在编译期间, 但有的错误只有在运行时才会发生。比如: 除数为0, 数组下标越界等

分类: 编译时异常(checked)和运行时异常(unchecked)

3. 异常的体系结构


upfile


主要介绍下运行时的异常

编译时的异常:在程序编译时就需要解决的异常, 不解决,编译不通过

upfile



常见的运行时的异常代码举例ExceptionTest.java

//ExceptionTest.java
package com.ylaihui.exception;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;
import org.junit.Test;

public class ExceptionTest {
	
	@Test
	public void test6(){
		// checked exception 编译时异常
		File file = new File("1.txt");
		// Unhandled exception type FileNotFoundException
		FileInputStream fis = new FileInputStream(file);
		
		// Unhandled exception type IOException
		int data = fis.read();
		while(data != -1){
			System.out.print((char)data);
			// Unhandled exception type IOException
			data = fis.read();
		}
		// Unhandled exception type IOException
		fis.close();
	}
	
	@Test
	public void test5(){
		// ArithmeticException  / by zero
		System.out.println(12/0);
	}
	
	@Test
	public void test4(){
		Scanner scan = new Scanner(System.in);
		int nint = scan.nextInt(); // 输入abc, 则 InputMismatchException
	}
	
	@Test
	public void test3(){
		// NumberFormatException
		String str = "add";
		Integer i = Integer.parseInt(str);
	}
	
	@Test
	public void test2(){
		// ClassCastException
		Object string = new String();
		Date d = (Date)string;
	}
	
	@Test
	public void test1(){
		// StringIndexOutOfBoundsException
		String str = "aaa";
		System.out.println(str.charAt(3));
	}
	
	public static void main(String[] args) {
		// java.lang.NullPointerException
//		String str = null;
//		System.out.println(str.charAt(1));
		
		// java.lang.ArrayIndexOutOfBoundsException
//		int[] arrary = new int[2];
//		System.out.println(arrary[2]);
	}
}

4. 异常处理try-catch-finally

在编写程序时,经常要在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。 过多的if-else分支会导致程序的代码加长、臃肿,可读性差,采用异常处理机制可以让代码更为简洁,提高代码的可读性。


Java异常处理Java采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。

两种处理异常的方式:(注意是处理异常)

try-catch-finally : 处理异常

throws: 继续向上抛异常(抛给调用者、父类、抛给Java虚拟机等...)


一、异常的处理:抓抛模型

    "抛":程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象,并将此对象抛出。

    一旦抛出对象以后,其后的代码就不再执行。

    关于异常对象的产生:

    ① 系统自动生成的异常对象

    ② 手动的生成一个异常对象,并抛出(throw)

    "抓":可以理解为异常的处理方式

    ① try-catch-finally  

    ② throws

二、try-catch-finally的使用

    try{

        //可能出现异常的代码,不一定出现异常

    }catch(异常类型1 变量名1){

        //处理异常的方式1

    }catch(异常类型2 变量名2){

        //处理异常的方式2

    }catch(异常类型3 变量名3){

        //处理异常的方式3

    }

    ....

    finally{

        //一定会执行的代码

    }

    说明:

    1. finally是可选的,可以不写finally模块

    2. 使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,在catch中进行匹配

    3. 一旦try中的异常对象匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的try-catch结构(在没有写finally的情况)。继续执行其后的代码

    4. catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。

    catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,报错Unreachable catch block for NumberFormatException.

    It is already handled by the catch block for Exception

    5. 常用的异常对象处理的方式:

    ① String  getMessage() 获取异常信息  

    ② printStackTrace() 打印栈信息

    6. 在try结构中声明的变量,再出了try结构以后,就不能再被调用

    注意:

    使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。

    相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。

//TryCatchTest.java
package com.ylaihui.exception;

import org.junit.Test;

public class TryCatchTest {

	@Test
	public void test1(){
		String str = "abc";
		try{
			Integer i = Integer.parseInt(str);
			System.out.println("not exec here!");
		}catch(NumberFormatException e){
			System.out.println("process NumberFormatException...");
//			System.out.println(e.getMessage());
//			System.out.println("----------------");
//			e.printStackTrace();
		}catch(NullPointerException e){
			System.out.println("process NullPointerException");
		}
		System.out.println("exec here!");
		// 在try结构中声明的变量,再出了try结构以后,就不能再被调用
//		System.out.println(i);
	}
	
	/*
	 process NumberFormatException...
	 exec here!
	 */
}


5. finally的使用

try-catch-finally中finally的使用:

1.finally是可选的

2.finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有

return语句等情况。不论有没有异常,finally中的代码都会执行。

3.像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的

释放。此时的资源释放,就需要声明在finally中。

4. try-catch-finally结构可以嵌套

开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。因为运行出异常了,说明代码写的有问题,需要修改代码,就算使用try-catch-finally处理了异常, 如果不改代码逻辑,还是会出现异常,还是要修改代码逻辑,让代码没有异常。

针对于编译时异常,我们一定要考虑异常的处理。

//TryCatchFinallyTest.java
package com.ylaihui.exception;

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

import org.junit.Test;

public class TryCatchFinallyTest {
	@Test
	public void test1(){
		FileInputStream fis = null;
		try {
			File file = new File("hello1.txt");
			fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null)  //如果不加该语句,文件不存在时,会报空指针异常
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

6.异常的处理throws + 异常类型

1. "throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,此对象就会被抛出给调用者。异常代码后续的代码,就不再执行。

比如Integer类的parseInt方法,如果输入的字符串"123a",包含英文字母,那么转换的时候会报异常

public static int parseInt(String s) throws NumberFormatException {

   return parseInt(s,10);

}

2. 体会:try-catch-finally:真正的将异常给处理掉了。

throws的方式只是将异常抛给了方法的调用者, 并没有真正处理异常。  

//ThrowsTest.java
package com.ylaihui.exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ThrowsTest {
	public static void main(String[] args){
		try{
			method2();
			
		}catch(IOException e){
			e.printStackTrace();
		}
		method3();	
	}
	
	public static void method3(){
		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("hello1.txt");
		FileInputStream fis = new FileInputStream(file);
		
		int data = fis.read();
		while(data != -1){
			System.out.print((char)data);
			data = fis.read();
		}
		
		fis.close();
		
		System.out.println("hahaha!");
	}
}

7. 子父类的方法抛异常

子类重写的方法抛出的异常类型小于等于父类被重写的方法抛出的异常类型

//OverrideTest.java
package com.ylaihui.exception;

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

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

	public void display(SuperClass s){
		try {
			s.method();
		} catch (IOException e) {  // SuperClass 抛出的异常是 IOException,处理 IOException 异常
			// 如果子类抛出的异常更大,那么 父类就无法 catch 子类的异常。
			// 所以禁止子类抛出的异常更大
			e.printStackTrace();
		}
	}
}

class SuperClass{
	public void method() throws IOException{
	}
}

class SubClass extends SuperClass{
	// 子类重写的方法抛出的异常类型小于等于父类被重写的方法抛出的异常类型
	public void method()throws FileNotFoundException{	
	}
}

8. 开发中如何选择异常处理的方式

开发中如何选择使用try-catch-finally 还是使用throws?

1.如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果

子类重写的方法中有异常,必须使用try-catch-finally方式处理。因为子类重写的方法抛出的异常类型小于等于父类被重写的方法抛出的异常类型

2. 执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws

的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理,这样可使代码更整洁,可读性更高。

9. 手动抛出异常 throw

手动抛出的异常对象 一般是 RuntimeException 或者 Exception

Exception 包含编译时的异常,需要处理异常

throw new RuntimeException("您输入的数据非法!");

throw new Exception("您输入的数据非法!");

//ThrowTest.java
package com.ylaihui.exception;

public class ThrowTest {
	public static void main(String[] args) {
		try {
			Student stu = new Student();
			stu.register(-1000);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}

class Student{
	int id;
	public void register(int id) throws Exception{
		if(id > 0)
			this.id = id;
		else
//			System.out.println("id is not valid!");
			// 此时不需要 try-catch,运行时异常不包含编译时异常
//			throw new RuntimeException("id is not valid!");
			// 此时需要 try-catch, Exception包含编译时异常,编译时可能不通过,需要处理
			throw new Exception("id is not valid!");
	}
}

10. 用户自定义异常类

如何自定义异常类?

 1. 继承于现有的异常结构:RuntimeException 、Exception (区别是运行时异常不需要try-catch处理 )

 2. 提供全局常量:serialVersionUID  序列版本号

 3. 提供重载的构造器(构造器 传入异常消息)

//DataNotValidException.java
package com.ylaihui.exception;

public class DataNotValidException extends RuntimeException {
    	static final long serialVersionUID = -7034897202145766939L;
    	
    	DataNotValidException(){}
    	DataNotValidException(String msg){
		super(msg);
	}
}
//UserDefinedException.java
package com.ylaihui.exception;

public class UserDefinedException {
    	public static void main(String[] args) {
    		try {
    			Student1 stu = new Student1();
    			stu.register(-1000);
    		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}

class Student1{
	int id;
	public void register(int id) throws Exception{
		if(id > 0)
			this.id = id;
		else
			throw new DataNotValidException("id is not valid!");
			// error
//			throw new String("id is not valid!");
	}
}


点赞 2

文章评论

欢迎您:

纸上得来终觉浅,绝知此事要躬行!

112 文章 59096 浏览 3 评论

联系我

  •   QQ:    361352119
  •  Email:  lisimmy@sina.com
  • 微信: