异常
Throwable的父类是Object 类,子类分为Error和Exception
Error表示什么异常,一般怎么处理
一般是严重错误,程序无法处理,在非正常递归调用时可能会导致StackOverflowError,
Exception表示什么异常,一般这么处理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HXmpsZ8q-1587722939140)(C:\Users\72038714\AppData\Roaming\Typora\typora-user-images\1587689092790.png)]
异常处理原则是:捕获并处理那些知道该如何处理的异常,抛出那些不知道如何处理的异常
捕获异常
捕获方式
(try{}catch{*****}finally{******} ),异常经过捕获后,执行会进入catch部分,finally最后都会执行。在执行完t ry catch整块之后,后面的代码会继续执行,不会终止。
1.多层异常捕获,需要先捕获子类异常,在捕获父类 异常,一次向上递进
finally 处理最后的资源类释放 流释放或者链接释放
非运行时异常需要提前进行异常处理,否则会有报语法错误
public class MyException {
public static void main(String[] args) {
try {
process1(null);
} catch (Exception e) {
e.printStackTrace();
}
try {
process2(null);
} catch (IOException e) {
e.printStackTrace();
}
try {
process3(null);
} catch (SQLException e) {
e.printStackTrace();
}
}
static String process1(String word){
System.out.println("这里是NullPointerException"+System.currentTimeMillis());
if(null == word){
throw new NullPointerException();
}
return word;
}
static void process2(String word) throws IOException {
System.out.println("这里是IOException"+System.currentTimeMillis());
throw new IOException();
//process3(word);
}
static void process3(String word) throws SQLException {
System.out.println("这里是SQLEXCEPTTION"+System.currentTimeMillis());
throw new SQLException();
//process2(word);
}
}
执行结果:
这里是NullPointerException1587692190353
这里是IOException1587692190354
这里是SQLEXCEPTTION1587692190354
java.lang.NullPointerException
at charpter08.MyException.process1(MyException.java:50)
at charpter08.MyException.main(MyException.java:29)
java.io.IOException
at charpter08.MyException.process2(MyException.java:58)
at charpter08.MyException.main(MyException.java:35)
java.sql.SQLException
at charpter08.MyException.process3(MyException.java:64)
at charpter08.MyException.main(MyException.java:41)
执行结果显示,三个调用的方法都执行了。依次抛出了他们的异常
异常抛出
异常的抛出使用throw关键字,需要再方法声明的最后。非运行时异常在声明时候需要处理
1.非运行时异常,如果在调用的方法中又抛出此类异常,或者在方法中声明了非运行时异常,那么该异常必须被立即处理,否则会出现语法错误。
static void process3(String word) throws SQLException {
System.out.println("这里是SQLEXCEPTTION"+System.currentTimeMillis());
throw new SQLException();
//process2(word);
}
第一种情况是,在process方法中,有可能会出现空指针异常,我们没有在该方法中处理,那么异常会抛出,在main方法中也没有被处理,那么程序在执行循环内的第一个元素后,抛出异常。程序退出,后面的代码不会执行。
package exceptionTest;
import java.io.IOException;
public class MyExceptionTest01 {
public static void main(String[] args) {
String[] names={"zhangsan",null,"lisi"};
for (String name:names) {
process(name);
}
System.out.println("未发现异常,所有程序执行结束!");
}
static void process(String name){
if(name.length()>0){
System.out.println("hello:"+name );
}
}
}
//执行结果
exceptionTest.MyExceptionTest01
hello:zhangsan
Exception in thread "main" java.lang.NullPointerException
at exceptionTest.MyExceptionTest01.process(MyExceptionTest01.java:17)
at exceptionTest.MyExceptionTest01.main(MyExceptionTest01.java:11)
Process finished with exit code 1
第二种情况是,我们在循环外面捕获,null后面的信息不会执行,循环外面的程序继续执行
package exceptionTest;
import java.io.IOException;
public class MyExceptionTest01 {
public static void main(String[] args) {
String[] names={"zhangsan",null,"lisi"};
try {
for (String name:names) {
process(name);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("未发现异常,所有程序执行结束!");
}
//方法process
static void process(String name){
if(name.length()>0){
System.out.println("hello:"+name );
}
}
}
第三种方法是在循环内部,方法外使用try catch,这样只有异常的数据会被跳过,其他程序正常执行。
在异常捕获与输出到控制台后,我们需要进一步对异常处理,实际的生产情况是,代码部署在了服务器,需要将日志统一收集与处理,便于后续的分析。监控线上任务的运行状况。
pom依赖
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.25version>
dependency>
log4j配置文件
log4j.rootLogger=DEBUG,console,dailyFile
log4j.additivity.org.apache=true
# 控制台(console)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.ImmediateFlush=true
log4j.appender.console.Target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 日志文件(logFile)
log4j.appender.logFile=org.apache.log4j.FileAppender
log4j.appender.logFile.Threshold=DEBUG
log4j.appender.logFile.ImmediateFlush=true
log4j.appender.logFile.Append=true
log4j.appender.logFile.File=/Users/wujiaqi/log/log.log4j
log4j.appender.logFile.layout=org.apache.log4j.PatternLayout
log4j.appender.logFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 回滚文件(rollingFile)
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.Threshold=DEBUG
log4j.appender.rollingFile.ImmediateFlush=true
log4j.appender.rollingFile.Append=true
log4j.appender.rollingFile.File=/Users/wujiaqi/log/log.log4j
log4j.appender.rollingFile.MaxFileSize=200KB
log4j.appender.rollingFile.MaxBackupIndex=50
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 定期回滚日志文件(dailyFile)
log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dailyFile.Threshold=DEBUG
log4j.appender.dailyFile.ImmediateFlush=true
log4j.appender.dailyFile.Append=true
log4j.appender.dailyFile.File=/Users/wujiaqi/log/log.log4j
log4j.appender.dailyFile.DatePattern='.'yyyy-MM-dd
log4j.appender.dailyFile.layout=org.apache.log4j.PatternLayout
log4j.appender.dailyFile.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 应用于socket
log4j.appender.socket=org.apache.log4j.RollingFileAppender
log4j.appender.socket.RemoteHost=localhost
log4j.appender.socket.Port=5001
log4j.appender.socket.LocationInfo=true
# Set up for Log Factor 5
log4j.appender.socket.layout=org.apache.log4j.PatternLayout
log4j.appender.socket.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# Log Factor 5 Appender
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000
# 发送日志到指定邮件
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
log4j.appender.mail.Threshold=FATAL
log4j.appender.mail.BufferSize=10
log4j.appender.mail.From = xxx@mail.com
log4j.appender.mail.SMTPHost=mail.com
log4j.appender.mail.Subject=Log4J Message
log4j.appender.mail.To= xxx@mail.com
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 应用于数据库
log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.database.URL=jdbc:mysql://localhost:3306/test
log4j.appender.database.driver=com.mysql.jdbc.Driver
log4j.appender.database.user=root
log4j.appender.database.password=123456
log4j.appender.database.sql=INSERT INTO LOG4J (Message) VALUES('=[%-5p] %d(%r) --> [%t] %l: %m %x %n')
log4j.appender.database.layout=org.apache.log4j.PatternLayout
log4j.appender.database.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
# 自定义Appender
#log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender
#log4j.appender.im.host = mail.cybercorlin.net
#log4j.appender.im.username = username
#log4j.appender.im.password = password
#log4j.appender.im.recipient = corlin@cybercorlin.net
#log4j.appender.im.layout=org.apache.log4j.PatternLayout
#log4j.appender.im.layout.ConversionPattern=[%-5p] %d(%r) --> [%t] %l: %m %x %n
测试代码
package exceptionTest;
import org.apache.log4j.Logger;
import java.io.IOException;
public class MyExceptionTest01 {
private static final Logger logger = Logger.getLogger(MyExceptionTest01.class.getClass());
public static void main(String[] args) {
logger.debug("debug");
logger.error("error");
String[] names={"zhangsan",null,"lisi"};
try {
for (String name:names) {
process(name);
}
} catch (NullPointerException e) {
e.printStackTrace();
logger.debug("process方法出现空指针异常"+e);
}
System.out.println("未发现异常,所有程序执行结束!");
}
static void process(String name){
if(name.length()>0){
System.out.println("hello:"+name );
}
}
}
引用的地址
log4J简介