##学习注解的案例(小明的计算机测试)演练过程时,代码出现了异常
异常代码
try{
//执行方法
method.invoke(c);
}catch (Exception e){
number++;
//捕获异常
//记录到文件中
bw.write(method.getName() + "方法出现异常了");
bw.newline();
bw.write("异常名称:" + e.getCause().getClass().getSimpleName());
bw.newline();
bw.write("异常原因" + e.getCause().getMessage());
bw.newline();
bw.write("--------");
bw.newline();
bw.flush();
e2.printStackTrace();
}
异常代码为:e.getCause().getClass().getSimpleName());
为空指针异常
C:UsersAdministrator.m2repositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar com.itcast.annotation.Demo.TestCheck
java.lang.NullPointerException
at com.itcast.annotation.Demo.TestCheck.main(TestCheck.java:42)
处理过程:
一、仔细对照了当前测试类中自己和老师的代码,发现方法调用位置传入参数错误
老师传入参数为被测试类对象:new Calculator
而我传入了类对象的Class对象:(new Calculator).getClass()
更改后,再次运行,依然报错
二、网络搜索代码信息和异常信息
未寻获解决方式
三、使用try{}catch(){}环绕整段可能出现错误的代码
将异常打印在控制台,使程序成功运行,生成了测试文件 bug.txt
控制台显示所有测试方法报错java.lang.NullPointerException
测试文件显示四个方法均未通过测试,和预期不符:
div方法出现异常了
add方法出现异常了
sub方法出现异常了
mul方法出现异常了
本次测试一共出现了4个异常
四、此时我想到,应该是被测试文件写错了
打开被测试文件Calculator一看,果然如此
出于写加减乘除的习惯,给每个方法定义了两个参数
//加法
public void add(int a,int b){
System.out.println("1 + 0 =" +(1+0));
}
可老师写的其实是
//加法
public void add(){
System.out.println("1 + 0 =" +(1+0));
}
不需要参数
这个错误在method调用invoke方法时,因为没有传入相应的两个变量而导致方法运行时空指针异常
五、总结
- 习惯导致认知信息错误
- 粗心大意
- 检查代码时只检查了当前类、未全面检查
白白耗费了时间,取得教训



