java基础核心技术学习笔记5--异常处理机制

package lesson05;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ExceptionTest {
	public static void main(String[] args)  {
		//1.Error
//		byte[] b = new byte [1024*1024*60];
//		main(new String[0]);
		//2.异常
		//1.程序执行到了出异常的位置
		//2.虚拟机JVM检测到数学异常
		//3.虚拟机在后台帮我们创建了ArithmeticException类的对象
		//4.将异常对象抛出
		//5.程序停止执行,打印异常现象
		//testExceptionObj();
		//testThrows();
		//testCatch();
		testMyOwnException();
//		int[] arr = new int[10];
//		System.out.println(arr[10]);//运行时异常:数组下标越界异常
		
		
	}
	public static void testExceptionObj () {
		int a = 10;
		int b = 0;
		
		int c = a/b;
		System.out.println("c="+ c);//运行时异常:数学异常
	}
	public static void testThrows() throws FileNotFoundException{
		InputStream in = new FileInputStream("aa.txt");//非运行时异常(编译时异常):找不到文件
	}
	public static String testCatch(){
		//注意:前面的catch块捕获的异常不能覆盖后面catch块中捕获异常
		try{
			//在try块中,检测尝试执行的代码
			int i = 10/2;
			//InputStream in = new FileInputStream("aa.txt");
			System.out.println("try");
			return "hello";	
			//多异常捕获,可以使用
		}
//		catch (FileNotFoundException e){
//			//在catch块中执行捕获异常后所要执行的代码,通常为处理异常的相应措施
//			System.out.println("FileNotFoundException");
//		}
		catch(ArithmeticException e){
			System.out.println("数学异常");
		}
		catch(Exception e){
			System.out.println("这里是用Exception捕获的");
		}finally{
			System.out.println("这里是必执行finally块");//1.不管try。。。catch走了哪一支,finally块里的语句都会被强制执行
												   //2.即使是在return后面,finally块也还是会执行
		}
		//异常捕获后,程序可以继续执行
		System.out.println("程序继续执行了");
		return "end";
	}
	public static void testMyOwnException(){
		MyOwnException e = new MyOwnException();
		throw e;
	}
}

package lesson05;

/*如何自定义异常
 * 1.继承已有的异常类
 * 如何抛出自定义异常
 * 1.使用throw关键字
 * throw一个异常类对象
 * */
public class MyOwnException extends RuntimeException{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

}
/*
 * 运行时异常和非运行时异常
 * 运行时异常:在编译时,不要求强制处理*/
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值