异常处理

java的中异常祖先是Throwable,Throwable的直接子类是Exception和Error。看图:
(Eclipse中,选中Throwable,按CTRL + T 便可出现此结构树。)
在这里插入图片描述
Error是错误的意思,这种错误一般是jvm运行产生的错误,出现这种错误,我们的程序不能解决,比如内存溢出oom,堆溢出等。这种错误,我们不必处理,直接让jvm抛出报错,我们没办法解决就不管了。

Exception中文意思是异常,Exception又分为运行时异常和编译时异常。
RuntimeException类及子类就是运行时异常
其余非RuntimeException都是编译时异常。

如下是常见的运行时异常:


public class TestException {

	/**
	 * 常见的运行时异常:
	 */
	// 1.数组下边越界异常:ArrayIndexOutOfBoundsException
	@Test
	public void test1() {
		int[] i = new int[10];
		System.out.println(i[11]);
	}

	// 2. 算术异常 :ArithmeticException
	@Test
	public void test2() {
		int i = 9;
		System.out.println(i / 0);
	}

	// 3. 类型转换异常:ClassCastException
	@Test
	public void test3() {
		Object obj = new Date();
		String str = (String) obj;
		System.out.println(str);
	}

	// 4. 空指针异常:NullPointerException
	@Test
	public void test4() {
		String str = new String();
		str = null;
		str.chars();
	}
}

运行时异常,我们也可以不进行处理,让jvm自己抛出异常,当然如果我们可以预见这种异常的话,最好在程序中进行判断检查,程序写健壮些,有的这种异常就可以避免了。

对于编译时异常,必须做处理,否则编译不通过。

处理异常
在这里插入图片描述
这个图非常全面描述了异常的处理方式。
处理方式一:try{ … }catch{ … } finally{ … }
这里不做过多介绍,相信大家写过代码的都会用了。
处理方式二:throws
throws + 异常类
声明异常,声明方法可能要抛出的异常类
用在方法上,在方法名的括号后面写,比如:

	public void testCollection() throws IOException{
		// 代码略
	}

处理方式三:throw
throw + 异常对象
抛出异常,手动抛出异常对象。用在方法内部。比如:

public class TestCollection {
	public static void main(String[] args) {

		TestCollection t = new TestCollection();
		t.testCollection(12, 0);
	}



	public int testCollection(int i, int j) {
		if (j == 0) {
			System.out.println("j是被除数,不能为0,算术异常");
			throw new ArithmeticException();
		}
		System.out.println(i / j);
		return i / j;
	}
}

一定要区分 throw 和 throws 的区别。

还有一点,如何自定义一个异常类

手动的抛出一个异常,除了抛出的是现成的异常类的对象之外,还可以抛出一个自定义的异常类的对象!
如何自定义一个异常类呢?
//1.自定义的异常类必须要继承现有的异常类
//2.提供一个序列号,提供几个重载的构造器

public class MyException extends Exception{
	
	static final long serialVersionUID = -70348975766939L;
	
	public MyException(){	}
	
	public MyException(String msg){
		super(msg);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值