练手:异常的种种问题

来源:互联网 发布:js splice 数组 编辑:程序博客网 时间:2024/05/17 02:41
/*
 * throw和throws有什么区别? 
 * try、catch、finally分别在什么情况下使用?
 * try-catch语句块用来捕获异常
 * try语句块只能有一个,而catch则可以有多个,catch必须紧跟try语句后,
 * 中间不能有其他任何代码.
 * finally,它规定的语句块无论如何都要执行,在一个try-catch中只能有一个finally.
 */
public class Test6 {
/*
 * 
 *
 *java使用throws语法声明当前方法有可能引起一个多多个异常;
 *使用语法:返回类型 方法名(参数列表)throws 异常类名1,异常类名2,异常类名3;
 *     throw适用于异常的再次抛出.
 *  异常的再次抛出是指昂捕获到异常的时候并不对它直接处理而是把它抛出留给上一层的调用来处理.
 *  
 * 
 * */
static void method()throws NullPointerException,
IndexOutOfBoundsException,ClassNotFoundException{
String str = null;//设置字符串的内容为null
int strLength = 0;//初始化字符串的长度赋值为0
strLength = str.length();//获取字符串的长度
System.out.println(strLength);
}
static void methodThrow()throws ClassNotFoundException{
try{
Class.forName("");
}catch(ClassNotFoundException e){
System.out.println("方法中把异常再次抛出");
throw e;
}
}
public static void main(String[] args) {
try{
method();
}catch(NullPointerException e){
System.out.println("NullPointerException异常");
e.printStackTrace();
}catch(IndexOutOfBoundsException e){
System.out.println("IndexOutOfBoundsException异常");
e.printStackTrace();
}catch(ClassNotFoundException e){
System.out.println("ClassNotFoundException异常");
e.printStackTrace();
}
System.out.println("-----------------");
try{
methodThrow();
}catch(ClassNotFoundException e){
System.out.println("主方法对异常进行处理");
}
}
}
0 0