异常错误

1.异常和错误都是类,基类Throwable 只实现了序列化接口。

1
2
3
public class Throwable implements Serializable {
...
}

2.printStackTrace()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void printStackTrace() {
printStackTrace(System.err);
}


public void printStackTrace(PrintStream s) {
printStackTrace(new WrappedPrintStream(s));
}

private void printStackTrace(PrintStreamOrWriter s) {
// Guard against malicious overrides of Throwable.equals by
// using a Set with identity equality semantics.
Set<Throwable> dejaVu = Collections.newSetFromMap(new IdentityHashMap<>());
dejaVu.add(this);

synchronized (s.lock()) {
// Print our stack trace
s.println(this);
StackTraceElement[] trace = getOurStackTrace();
for (StackTraceElement traceElement : trace)
s.println("\tat " + traceElement);

// Print suppressed exceptions, if any
for (Throwable se : getSuppressed())
se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);

// Print cause, if any
Throwable ourCause = getCause();
if (ourCause != null)
ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
}
}

3.捕获异常 (都很熟悉)

1
2
3
4
5
6
7
8
try{
}catch(IOException e1){
e1.printStackTrace();
}catch(Exception e2){
e2.printStackTrace();
}finally{
//
}

4.抛出异常

1
2
3
4
5
//使用throw + 异常对象
Exception exception2=new Exception();
throw exception2;

或者throw new Exception();

5.Java异常体系

Java标准库定义的常用异常包括:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Exception

├─ RuntimeException
│ │
│ ├─ NullPointerException
│ │
│ ├─ IndexOutOfBoundsException
│ │
│ ├─ SecurityException
│ │
│ └─ IllegalArgumentException
│ │
│ └─ NumberFormatException

├─ IOException
│ │
│ ├─ UnsupportedCharsetException
│ │
│ ├─ FileNotFoundException
│ │
│ └─ SocketException

├─ ParseException

├─ GeneralSecurityException

├─ SQLException

└─ TimeoutException

6.assert关键字

assert用来开发的时候使用,如果断言失败会抛出异常

1
2
assert x>0; 
assert x>=0 : "x must >= 0";

JVM默认关闭断言,开启断言需要编译时额外参数,实际上一般不用断言,都是使用JUnit。

7.使用Logger日志系统代替System.out.println()

1
2
3
4
5
Logger logger = Logger.getGlobal();
logger.info("start process...");
logger.warning("memory is running out...");
logger.fine("ignored.");
logger.severe("process will be terminated...");

logger一共有七个等级

  • SEVERE

  • WARNING

  • INFO

  • CONFIG

  • FINE

  • FINER

  • FINEST

    Config和下面的都不会打印出来。

实际上一般也不用,也需要额外的参数。

8.日志库Commons Logging

Commons Logging定义了6个日志级别:

  • FATAL
  • ERROR
  • WARNING
  • INFO
  • DEBUG
  • TRACE

使用的话Log log = LogFactory.getLog(Class名);

9.广泛使用的Log4j日志系统,xml配置麻烦,搭配SpringBoot应该会简单吧

10.和89对应的分别是SLF4J和Logback