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这两个关键字接近,不过意义不一样,有如下区别:
- throws 出现在方法声明上,而throw通常都出现在方法体内。
- 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