异常处理

聪明出于勤奋,天才在于积累。——华罗庚


本讲内容:异常处理


一、基本概念

当出现程序无法控制的外部环境问题(用户提供的文件不存在,文件内容损坏,网络不可用……)时,java就会用异常对象来描述。


二、java中用2种方法处理异常:

1、在发生异常的地方直接处理意见;try--catch

2、将异常抛给调用者,让调用者处理(都抛上一级最终是虚拟机处理);throws Exception


三、异常分类(也可分检查性异常和非检查性异常)

1、检查性异常:java.lang.Exception

2、运行期异常:java.lang.RuntimeException

3、错误:java.lang.Error

java.lang.Exception和java.lang.Error继承java.lang.Throwable,而java.lang.RuntimeException继java.lang.Exception


下面是非检查性异常(Error及其子类和RuntemeException及其子类)

异常 异常对应的运行错误
ArithmeticException算术错误,譬如被0除
ArrayIndexOutOfBoundsException数组下标越界
ClassCastException无效的类型转换
EmptyStackException空栈异常
IndexOutOfBoundsException某些类型的下标越界
NegativeArraySizeException用负数创建数组
NullPointerException使用空引用错误
NumberFormatException字符串到数字格式的无效转换
StringIndexOutOfBounds尝试在一个字符串边界之外进行索引

下面是检查性异常(Exception及其除RuntemeException以外的所有子类)

异常异常对应的运行错误
ClassNotFoundException未找到欲装载的类
CloneNotSupportedException尝试复制一个没有实现Cloneable接口的对象
FileNotFoundException未找到指定的文件或目录
IllegalAccessException对一个类的访问被拒绝
IOException输入、输出错误
InterruptedException线程在睡眠、等待、或因其他原因暂停时被其他线程打断


示例一:

public class Text {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		try {
			System.out.print("请输入第一个数");
			int one=in.nextInt();
			System.out.print("请输入第二个数");
			int two=in.nextInt();
			System.out.println("两数相除结果为:"+one/two);
		} catch (InputMismatchException e) {//输入匹配异常
			System.out.println("你应该输入整数");
			e.printStackTrace();//打印异常的具体信息
		}catch(ArithmeticException e){//算术异常
			System.out.println("除数不能为0");
		}catch(Exception e){
			System.out.println("我是不知名异常");//相当于没处理异常
			e.printStackTrace();
		}finally{
			//最终将要执行的一些代码,譬如关闭什么释放资源
			System.out.println("这是finally!哈哈");
			in.close();
		}
		System.out.println("程序结束啦");
	}

}

打印:




示例二:自定义异常

//自定义异常(当java库没有满足我们要求的异常)
public class DrunkException extends Exception {
	
	public DrunkException() {
		
	}
	
	public DrunkException(String message) {
		super(message);
	}

}


异常链

/**
 * test1():拋出“喝大了”异常
 * test2():调用test1(),捕获“喝大了”异常,并且包装成运行时异常,继续抛出
 * main方法中,调用test2(),尝试捕获test2()方法抛出异常
 *
 */
public class Text {
	public static void main(String[] args) {
		Text t=new Text();
		try {
			t.test2();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void test1() throws DrunkException{
		throw new DrunkException("喝酒別开车");
	}
	
	public void test2(){
		try {
			test1();//因为会抛出异常,所以要捕获
		} catch (DrunkException e) {
			RuntimeException exception=new RuntimeException(e);
			throw exception;
		}
	}

}
打印:



本讲就到这里,Take your time and enjoy it


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值