异常处理

intro

debug的重要方法就是对程序的异常进行报错、处理。而捕获、处理、抛错就是著名的异常处理三大步。

Exception类


Excetption类提供错误类的数据结构,当系统发生错误,会将错误类型(异常)抛出,能被catch捕获。错误类型以Exception结尾。
注意Exception类在java.lang包中哦,所以不需要任何import

try,catch捕获

前者检查代码,后者检查错误类型。

public class ExceptionTest{
	public static void main(String args[]) {
		try{
			int a[] = new int[2];
			System.out.println("Access element three: " + a[3]);
		}catch(ArrayIndexOutOfBoundException e) {
			System.out.println("Exception thrown :" + e);
		}
		System.out.println("Out of the block");
}
}
# output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
Out of the block

当然这里多个catch捕获多个异常了,就不赘述了。

finaly关键字

无论是否出现异常,finally中的代码都会被执行

public class ExceptionTest{
	public static void main(String args[]) {
		try{
			int a[] = new int[2];
			System.out.println("Access element three: " + a[3]);
		}catch(ArrayIndexOutOfBoundException e) {
			System.out.println("Exception thrown :" + e);
		}finally{System.out.println("Out of the block");
		}
}
}

throws/throw关键字

如果想一个函数实现功能、另一个函数实现异常处理,那么最好的方法就是实现功能的函数出现异常时,将异常抛到另一个函数进行异常处理。这是代码简洁的一种体现。

public class TestException{
	public static void main(String[] args) {
		HandleException();
	}

	private static void HandleException(){
		try{
			DoSomething();
		}catch(ArrayIndexOutOfBoundException e){
			e.printStackTrace();
		}
	}
	private static void DoSomething()throws ArrayIndexOutOfBoundException{
		int[] a = new int[2];
		System.out.println("Access element three :" + a[3]);
	}
}

throws与throw这两个关键字接近,不过意义不一样,有如下区别:

  1. throws 出现在方法声明上,而throw通常都出现在方法体内。
  2. throws 表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某个异常对象。
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}

组合拳

throw,try,catch,finally,自己试一下吧~


Reference

[1] https://how2j.cn/k/exception/exception-trycatch/336.html#nowhere
[2] https://www.runoob.com/java/java-exceptions.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值