java throw 抛出异常不带堆栈 java抛出异常代码
转载
Java中两种抛出异常的方式
在Java中有两种抛出异常的方式,一种是throw,直接抛出异常,另一种是throws,间接抛出异常。
直接抛出异常是在方法中用关键字throw引发明确的异常。当throw被执行时,其后语句将不再执行,执行流程将直接寻找catch语句并进行匹配。这种错误不是出错产生,而是人为的抛出。throw抛出异常的格式为
throw ThrowableObject; //例如: throw new ArithmeticException(); |
在Java的异常处理模块中,所有抛出的异常都必须要有对应的“异常处理模块”。也就是说,如果在程序中抛出一个异常,那么在方法中就必须要捕获这个异常。
public class Test {
public static void main(String[] args) {
System.out.print("now ");
try{
System.out.print("is ");
throw new NullPointerException();
}catch (NullPointerException e){
System.out.print("the ");
}
System.out.print("time");
}
}
now is the time
|
如果一个方法可能导致一个异常但不处理它,此时要求在方法声明中包含throws子句,通知潜在调用者,在发生异常时沿着调用层次向上传递,由调用它的方法来处理这些异常,这类异常称为申明异常。实例如下
public class Test {
private static void p() throws ArithmeticException{
int i;
i = 4/0;
}
public static void main(String[] args) {
try {
p();
}catch (ArithmeticException e){
System.out.println("除0错误");
}
}
}
|
在本实例中,语句I = 4/0;将产生异常,产生异常后方法p()并不进行处理,而是由调用p()的main方法进行处理。
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。