計算器測驗并且捕獲其例外
- 一.計算器類
- 二. 注解
- 三. 測驗
- 四. 運行結果
- 五. 例外
一.計算器類
步驟:
1.加法
2.減法
3.乘法
4.除法
package FanShe.annotation;
//定義的計算器類
public class Calculator {
@check
//加法
public void add(){
String str=null;
str.toString();
System.out.println("1+0="+(1+0));
}
@check
//減法
public void sub(){
System.out.println("1-0="+(1-0));
}
@check
//乘法
public void mul(){
System.out.println("1*0="+(1*0));
}
@check
//除法
public void div(){
System.out.println("1/0="+(1/0));
}
public void show(){
System.out.println("永無bug");
}
}
二. 注解
package FanShe.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface check {
}
三. 測驗
步驟
1.創建計算器物件
2.獲取位元組碼檔案
3.獲取所有方法
4.判斷方法是否有check注解
5.捕獲例外
package FanShe.annotation;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
*簡單的測驗框架
* 當主方法執行后,會自動監測的所有方法(加了check注解的方法),判斷方法是否例外,記錄到檔案中
*/
public class CalculatorTest {
public static void main(String[] args) throws ClassNotFoundException, IOException {
//1.創建計算器物件
Calculator c=new Calculator();
//2.獲取位元組碼檔案
Class cls = c.getClass();
//3.獲取所有方法
Method[] methods = cls.getMethods();
//出現例外的次數
int number=0;
BufferedWriter buff=new BufferedWriter(new FileWriter("bug.txt"));
//4.判斷方法是否有check注解
for (Method method : methods) {
//5.有,執行
if(method.isAnnotationPresent(check.class)){
try {
method.invoke(c);
} catch (Exception e) {
// 6.捕獲例外
//記錄到檔案中
number++;
//獲取例外的方法
buff.write(method.getName()+"方法出例外了");
buff.newLine();
//獲取例外的名稱
buff.write("例外的名稱"+e.getCause().getClass().getSimpleName());
buff.newLine();
//獲取例外的原因
buff.write("例外的原因"+e.getCause().getMessage());
buff.newLine();
buff.write("-------------------");
buff.newLine();
}
}
}
buff.write("本次一共出現"+number+"次例外");
buff.flush();
buff.close();
}
}
四. 運行結果
1*0=0
1-0=1
五. 例外
add方法出例外了
例外的名稱NullPointerException
例外的原因null
-------------------
div方法出例外了
例外的名稱ArithmeticException
例外的原因/ by zero
-------------------
本次一共出現2次例外
作者:Aimee.潔
本文著作權歸作者和CSDN共有,歡迎轉載,未經作者同意必須保留此版宣告,否則保留追究法律責任的權利,
@喜歡的點贊關注,評論區留下寶貴的意見吶??~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/258173.html
標籤:java
