Java异常

一、Java中的异常分类

Java中所有异常的父类是Exception分为受理异常和非受理异常,受检异常是:SQLException、IQException、ClassNotFoundException、、、、;非受检异常是:RuntimeException以下的子类,也是Exception的子类,RuntimeException作为非受理异常它的子类有:NullPointException、ArithmeticException、EvenException、、、、、例如以下:

1.非受检异常(运行异常)

package oneWeek;

public class Except {
	public static void main(String[] args) {
		Except exc = new Except();
		int v = exc.margin(20, 0);
	}
	public int margin(int a,int b){
		int result=a/b;
		return result;
	}
}

通过运行程序,执行的结果是:Exception in thread "main" java.lang.ArithmeticException: / by zero
at oneWeek.Except.margin(Except.java:9)
at oneWeek.Except.main(Except.java:6)

因为它的被除数为零,所以出现算术异常即非处理异常

还有最常见的空指针异常例如:

package oneWeek;

import javax.swing.JFrame;

public class NullPoint {
	static JFrame jf;
	public static void main(String[] args) {
		jf.setVisible(true);
	}
}

其执行的结果是:Exception in thread "main" java.lang.NullPointerException
at oneWeek.NullPoint.main(NullPoint.java:8)

是由于没有给定相关的地址,所以出现空指针异常

2.受检异常(非运行异常)

但凡继承了Exception不继承RuntimeException都是受检异常;

Java异常处理机制

1>捕获异常(将异常捕获)

1.try—catch语句

在Java中,非运行异常一般通过try-catch语句捕获,一般语法形式为:

try{
//可能发生异常的代码程序
}catch{
//执行异常操作
}
catch{
//执行异常操作
}.......
finally{
处理完try与catch操作完后收尾操作,异常统一出口
}

我们用简单的程序来试试,例如:

package oneWeek;

public class Except {
	public static void main(String[] args) {
		Except exc = new Except();
		int v = exc.margin(20, 0);
	}
	public int margin(int a,int b){
		int result = 0;
		try{
			result=a/b;
		}catch(ArithmeticException e){
			e.printStackTrace();
		}finally{
			System.out.println("程序正常结束");
		}
		return result;		
	}
}
其执行的结果是:java.lang.ArithmeticException: / by zero
at oneWeek.Except.margin(Except.java:11)
at oneWeek.Except.main(Except.java:6)
程序正常结束

由此可见,尽管程序出现异常,finally最终还得执行

2>抛出异常(将异常抛出)

同上,抛出异常我们任然可以用代码来解释:

package oneWeek;

public class ThrowException {
	public static void main(String[] args) throws ArithmeticException{
		int i = 8;
		int j = 0;
		try{
			System.out.println("i/j的值是"+i/j);
		}catch(ArithmeticException e){
			throw new ArithmeticException();
		}finally{
			System.out.println("执行了finally语句");
		}
	}
}
输出结果是:执行了finally语句
Exception in thread "main" java.lang.ArithmeticException
at oneWeek.ThrowException.main(ThrowException.java:10)

先执行了finally语句,在执行了异常抛出。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值