此时引入 try/catch/finally(捕获/处理/结束)
我们假设引入一个最简单的异常:算术异常
public class ForthClass {
public static void main(String[] args) {
int a = 1/0;
System.out.println(a);
System.out.println("测试");
}
}
try{
try{
int a = 1/0;
}catch (ArithmeticException e){ //括号中填写的是异常名 也可以只写Exception
e.printStackTrace(); //打印异常,不过输出的是红字,然后继续运行
}finally {
System.out.println("测试finally"); //无论上面发生了啥,走没走catch 最后都会执行finally块
}
异常也可以进行嵌套,请看下面一段代码:
try{
try{int a = 1/0;
}catch (ArithmeticException e){
System.out.println("可以嵌套");
e.printStackTrace();
}
int[] b = new int[10];
b[20] = 100;
}catch (ArithmeticException e){
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("数组越界");
}finally {
System.out.println("测试finally");
}
System.out.println("hello");
}
先编写一个有异常语句的方法:
public static void test() throws Exception {
//模拟抛出异常
try{
int[]b = new int[10];
b[30] = 200;
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
throw new Exception("数组越界"); //throw就是抛出异常的语句
}finally {
System.out.println("测试");
}
}
public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
//在上述语句中,throws后为抛出异常,谁调用这个方法异常就由谁来处理
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
}
为什么要引入日志?
在实际开发中,不可能会有人无时无刻关注服务器的输出内容,需要让程序自己把控制台的内容记录下来。
只要在出现问题的时候,开发人员可以查询log记录。
日志工具类:
public class SecClass {
//全部大写
final static Logger LOGGER = Logger.getLogger(SecClass.class); //括号里是当前类的类名
public static void main(String[] args) {
LOGGER.info("test");
LOGGER.debug("测试");
LOGGER.error("错误");
LOGGER.warn("警告");
try {
int a = 1/0;
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e); //输出error
}
}
}
样例输出:
debug.log
error.log
info.log
warn.log
代码编写:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThirdClass {
final static Logger LOGGER = LoggerFactory.getLogger(com.lanou.ThirdClass.class); //同log4j
public static void main(String[] args) {
LOGGER.debug("测试模式");
LOGGER.info("信息");
LOGGER.warn("警告");
LOGGER.error("错误");
String name = "张三";
int age = 22;
String address = "大连";
String birthday = "1999-3-20";
String id = "123456789";
LOGGER.info("我叫:{},今年:{},家住在:{},生日是:{},身份证号是:{}",name,age,address,birthday,id); //方便输出法
}
}
样例输出:
debug.log
error.log
info.log
warn.log
链接:https://pan.baidu.com/s/1IlFLjm1wKG_JjHn1w4B8QA
提取码:11ws
1.slf4j-api-1.7.25.jar
链接:https://pan.baidu.com/s/1aesO8I6Xr75CYWO2uViOmg
提取码:ncby
2.slf4j-log4j12-1.7.25.jar
链接:https://pan.baidu.com/s/1OFzPby6ngEa1cacoU5Tm6A
提取码:2zzl
链接:https://pan.baidu.com/s/1-3z0ShEmuaY8JAWAOclBsg
提取码:w1hr
链接:https://pan.baidu.com/s/1GaZfm5fJWYAt6KbmlP48QQ
提取码:6g87
原文:https://www.cnblogs.com/lzb1234/p/10554257.html