第二章:异常处理:try-catch-finally、throws、throw

package com.atguigu.java1;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;

import org.junit.Test;

/*
 * 一、
 * 异常的体系结构:
 * java.lang.Throwable(广义上的异常)
 *    |----java.lang.Error(错误):一般不编写针对性代码进行处理
 *    |----java.lang.Exception(狭义上的异常):需要编写代码进行处理
 *    		|----编译时异常(checked)
 *   			 |----IOException
 *   				|----FileNotFoundException
 *   			 |----ClassNotFoundException
 *    		|----运行时异常(unchecked,RuntimeException)
 *    			 |----NullPointerException:空指针异常
 *    			 |----ArrayIndexOutOfBoundsException:数组角标越界异常
 *    			 |----ClassCastException:类型转换异常
 *   			 |----NumberFormatException:数值转换异常(数字格式化异常)
 *       		 |----InputMismatchException:输入不匹配异常
 *    			 |----ArithmeticException:算数异常
 *  
 *  面试题:常见的异常都有哪些?举例说明。
 *    
 * 
 */
public class ExceptionTest {
	// *************以下是编译时异常*******************
	// @Test
	// public void test6() {
	// File file = new File("hello.txt");
	// FileInputStream fis = new FileInputStream(file);// FileNotFoundException
	//
	// int data = fis.read();// IOException
	// while (data != -1) {
	// System.out.print((char) data);
	// data = fis.read();// IOException
	// }
	//
	// fis.close();// IOException
	//
	// }

	// *************以下是运行时异常*******************
	// ArithmeticException:算数异常
	@Test
	public void test5() {
		int a = 10;
		int b = 0;
		System.out.println(a / b);// ArithmeticException:算数异常
	}

	// InputMismatchException:输入不匹配异常
	@Test
	public void test4() {
		Scanner scan = new Scanner(System.in);
		int i2 = scan.nextInt();
		System.out.println(i2);

		scan.close();
	}

	// NumberFormatException:数值转换异常(数字格式化异常)
	@Test
	public void test3() {
		String s2 = "123";
		Integer integer = Integer.parseInt(s2);// ok的

		String s3 = "123A";
		int num = Integer.parseInt(s3);// NumberFormatException:数值转换异常(数字格式化异常)

	}

	// ClassCastException:类型转换异常
	@Test
	public void test2() {
		// String s = new Date();//这个就不算是异常了(Exception),编译时就出现问题,根本不符合语法规则
		Object o = new Date();// 多态
		String s = (String) o;// ClassCastException

	}

	// ArrayIndexOutOfBoundsException:数组角标越界异常
	@Test
	public void test1() {
		int[] i1 = new int[10];
		System.out.println(i1[10]);
	}

	// NullPointerException:空指针异常
	@Test
	public void test() {
		// int[] i = null;
		// System.out.println(i[1]);//NullPointerException

		String s = "abc";
		System.out.println(s.charAt(0));// a
		String s1 = null;
		System.out.println(s1.charAt(0));// NullPointerException
	}
}
package com.atguigu.java1;

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

import org.junit.Test;

/*
 * 一、异常的处理:抓抛模型
 * 
 * 过程一:”抛“:程序在正常的执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。
 * 并将此对象抛出。
 * 一旦抛出对象之后,其后的代码就不再执行。
 * 
 * 		关于异常对象的产生:①系统自动生成异常的对象
 * 						  ②手动的生成一个异常对象,并抛出(throw)
 * 
 * 过程二:”抓“:可以理解为异常的处理方式:①try-catch-finally ②:throws
 * 
 * 二、try-catch-finally的使用
 * 
 * try{
 *   	//可能出现异常的代码
 * }catch(异常类型1 变量1){
 * 		//处理异常的方式1
 * }catch(异常类型2 变量2){
 * 		//处理异常的方式2
 * }catch(异常类型3 变量3){
 * 		//处理异常的方式3
 * }
 * ......
 * finally{
 * 		//一定会执行的代码
 * }
 * 
 * 说明:
 * 1.finally是一个可选的,不一定要写。
 * 2.使用 try 将可能出现的异常代码包装起来,在执行过程中。一旦出现异常,就会生成一个对应异常类的对象,
 *   根据此对象的类型,去catch中进行匹配。
 * 3.一旦try中的异常对象,匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,
 * 就跳出当前的try-catch结构,(在没有写finally的前提下),继续执行其后的代码。
 * 4.catch中的异常类型,如果没有子父类关系,则谁声明在上谁声明在下无所谓,
 * catch中的异常类型如果满足子父类关系,子类在上,父类在下,否则报错
 * 5.常用的异常对象处理方式,在catch打括号内:①getMessage()方法(返回字符串) ②printStackTrace()方法
 * 6.在try结构中定义声明的变量,在除了try之后就不能调用了。(想用的话就在外面声明一下)
 * 
 * 7.try-catch-finally可以相互嵌套
 * 
 * 体会1:使用try -catch -finally处理编译时异常,使得程序在编译时就不再报错,但是在运行时仍可能报错。
 * 		相当于我们使用try-catch-finally结构编译时可能出现的异常延迟至运行时出现。
 * 
 * 体会2:开发中。由于运行时异常比较常见,所以我们就不针对运行时异常进行try-catch-finally处理了。
 * 		针对编译时异常,我们说一定要考虑异常的处理。
 * 
 * 
 */
public class ExceptionTest1 {
	
	@Test
	public void test6() {
		File file = new File("hello.txt");
		try {
			FileInputStream fis = new FileInputStream(file);// FileNotFoundException

			int data = fis.read();// IOException
			while (data != -1) {
				System.out.print((char) data);
				data = fis.read();// IOException
			}

			fis.close();// IOException
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test1() {
		String s3 = "123";

		s3 = "abc";
		try {
			int num = Integer.parseInt(s3);// NumberFormatException:数字格式化异常
			System.out.println("hello-----1");
		} catch (NumberFormatException e) {
			// System.out.println("出现数值转换异常了,别着急");
			// String getMessage():
			// System.out.println(e.getMessage());
			// printStackTrace();
			e.printStackTrace();
		} catch (NullPointerException e) {
			System.out.println("出现空指针异常了");
		} catch (Exception e) {//
			System.out.println("出现异常了");
		}
		System.out.println("hello-----2");
	}
}
package com.atguigu.java1;

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

/*
 * 异常处理方式2:throws + 异常类型
 * 
 * 1."throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
 *   一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后的异常类型
 *   时,就会被抛出。异常代码后面的代码就不会被执行了。
 *   
 * 2.体会1: try-catch-finally:真正的将异常处理掉了。
 * 			throws的方式只是将异常抛给了方法的调用者。并没有真正地将异常处理掉。
 * 
 * 3.开发中如何选择try-catch-finally还是throws?
 * 		3.1如果父类中被重写的方法没有使用throws处理异常,那么他的子类中重写的方法也不能使用throws进行
 * 		异常处理,意味着如果子类重写的方法有异常,只能通过try-catch-finally的方式进行异常的处理。
 * 		3.2执行的方法a中,先后又调用了另外几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws
 * 		的方式进行处理。而执行的方法a中可以考虑使用try-catch-finally的方式进行处理。
 * 
 * 
 */
public class ExceptionTest2 {

	public static void main(String[] args) {

		try {
			method2();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

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

	public static void method1() throws FileNotFoundException, IOException {

		File file = new File("hello.txt");
		FileInputStream fis = new FileInputStream(file);// FileNotFoundException
		int data = fis.read();// IOException
		while (data != -1) {
			System.out.print((char) data);
			data = fis.read();// IOException
		}
		fis.close();// IOException

	}

}
package com.atguigu.java1;

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

import org.junit.Test;

/*
 * try-catch-finally结构中finally的使用:
 * 
 * 1.finally是一个可选的
 * 
 * 2.finally中声明的是一定会被执行的代码。即使catch中出现了异常,try中有return语句(应该结束方法),
 * catch中有return语句(应该结束方法)等情况。也一定会执行。
 * 
 * 3.像数据库连接,输入输出流,网络编程中的Socket等资源,JVM是不能自动回收的,我们需要自己手动进行资源的释放
 * 此时资源的释放,就需要声明在finally中。
 * 
 * 
 */
public class FinallyTest {
	@Test
	public void test3(){
		
		FileInputStream fis = null;
		try {
			File file = new File("hello1.txt");
			fis = new FileInputStream(file);// FileNotFoundException
			int data = fis.read();// IOException
			while (data != -1) {
				System.out.print((char) data);
				data = fis.read();// IOException
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	@Test
	public void test2(){
		int num = method();
		System.out.println(num);
	}
	public int method(){//有返回值
		try{
			int[] arr = new int[10];
//			System.out.println(arr[10]);
			return 1;
		}catch(ArrayIndexOutOfBoundsException e){
			e.printStackTrace();
			return 2;
		}finally{
			System.out.println("我一定会被执行");
		}
	}
	
	
//	@Test
//	public void test1(){
//		try{
//		int a = 10;
//		int b = 0;
//		System.out.println(a / b);
//		}catch(ArithmeticException e){
//			e.printStackTrace();
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		System.out.println("我好帅啊");
//		finally{
//			System.out.println("我好帅啊");
//		}
//	}
}
package com.atguigu.java2;

public class StudentTest {
	public static void main(String[] args) {
		Student s = new Student();

		try {
			s.redist(-1001);
			System.out.println(s);
		} catch (Exception e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}

	}
}

class Student {

	private int id;

	public void redist(int id) throws Exception {
		if (id > 0) {
			this.id = id;
		} else {
			// System.out.println("数据非法");
			// 手动抛出异常对象:throw
			// throw new RuntimeException("你输入的数据是非法的");
			// throw new Exception("你输入的数据是非法的");//手动抛出异常对象:throw
			throw new MyException("不能输入负数");
		}
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";

	}

}
package com.atguigu.java2;
/*
 * 如何自定义异常类?
 * 		1.需要继承于现有的异常类:RuntimeException Exception
 * 		2.提供一个全局常量serialVersionUID:对类的一个标识
 * 		3.提供重载的构造器
 */
public class MyException extends Exception{
	
	static final long serialVersionUID = -43536354634576L;
			
	public 	MyException(){
		
	}	
	public MyException(String msg){
		super(msg);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值