java 异常测试
【代码示例】
package com.linhuaming.test;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
/**
* 异常测试
*/
public class ExceptionTest {
// private final static Logger logger = LoggerFactory.getLogger(ExceptionTest.class);
private final static Logger logger = LoggerFactory.getLogger(ExceptionTest.class);
/**
* 主方法
* @param args
*/
public static void main(String[] args) {
// UserTest.methodA();
System.out.println("main()");
try{
methodA();
}catch (Exception e){
logger.error(e.getMessage(),e);
throw new RuntimeException("执行methodA()方法失败");
}
}
public static void methodA(){
System.out.println("methodA()");
try{
methodB();
}catch (Exception e){
logger.error(e.getMessage(),e);
throw new RuntimeException("执行methodB()方法失败");
}
}
public static void methodB(){
System.out.println("methodB()");
try{
methodC();
}catch (Exception e){
logger.error(e.getMessage(),e);
throw new RuntimeException("执行methodC()方法失败");
}
}
public static void methodC(){
System.out.println("methodC()");
int x = 1;
int y = 0;
double z = x/y;
System.out.println(z);
}
}
【运行结果】
main()
methodA()
methodB()
methodC()
七月 14, 2023 11:46:07 上午 com.sun.org.slf4j.internal.Logger error
严重: / by zero
java.lang.ArithmeticException: / by zero
at com.linhuaming.test.ExceptionTest.methodC(ExceptionTest.java:54)
at com.linhuaming.test.ExceptionTest.methodB(ExceptionTest.java:43)
at com.linhuaming.test.ExceptionTest.methodA(ExceptionTest.java:33)
at com.linhuaming.test.ExceptionTest.main(ExceptionTest.java:23)
七月 14, 2023 11:46:15 上午 com.sun.org.slf4j.internal.Logger error
严重: 执行methodC()方法失败
java.lang.RuntimeException: 执行methodC()方法失败
at com.linhuaming.test.ExceptionTest.methodB(ExceptionTest.java:46)
at com.linhuaming.test.ExceptionTest.methodA(ExceptionTest.java:33)
at com.linhuaming.test.ExceptionTest.main(ExceptionTest.java:23)
七月 14, 2023 11:46:20 上午 com.sun.org.slf4j.internal.Logger error
严重: 执行methodB()方法失败
java.lang.RuntimeException: 执行methodB()方法失败
at com.linhuaming.test.ExceptionTest.methodA(ExceptionTest.java:36)
at com.linhuaming.test.ExceptionTest.main(ExceptionTest.java:23)
Exception in thread "main" java.lang.RuntimeException: 执行methodA()方法失败
at com.linhuaming.test.ExceptionTest.main(ExceptionTest.java:26)
linhuaming