一、起因
昨天在本地跑了一个的爬虫程序,下午很长一段时间服务都是正常的,第二天早上到公司发现服务中断了,报的错误如下:
Handler dispatch failed; nested exception is org.jsoup.UncheckedIOException: java.net.SocketTimeoutException: Read timeout] with root cause
二、经过
然后看了下代码,确定是有用try-catch捕捉每次请求爬取的异常,那线程中断的可能就是抛出来的不是Exception,而是抛出了Error
,看了下源码,果然是这样。
Jsoup1.1.12版本,抛出的不能检查的IOException继承Error
…
public class UncheckedIOException extends Error {
public UncheckedIOException(IOException cause) {
super(cause);
}
public IOException ioException() {
return (IOException) getCause();
}
}
按理说,抛出Error不应该由程序主动抛出,抛出Error应该算是个Bug了。于是去Github上验证了下,果然最新的版本是1.1.13,修复了这个问题。
Jsoup1.1.13代码
public class UncheckedIOException extends RuntimeException {
public UncheckedIOException(IOException cause) {
super(cause);
}
public IOException ioException() {
return (IOException)this.getCause();
}
}
三、解决方法
方法1、捕捉Error
try{
}catch(Exception e){
}catch(Error e){
}
方法2、升级Jsoup版本,从1.1.12升级到1.1.13(建议使用)
四、温故知新
1、继承关系
2、从源码的角度看NullPointerException
测试程序
很明显,我们都能看出将出抛出空指针异常。
Exception in thread "main" java.lang.NullPointerException
那么?异常是由谁抛出来的,是如何抛出来的?
public class Test {
private String name = "test";
public static void main(String[] args) {
Test test = null;
test.getName();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
NullPointerException源码,从注释描述中可以看出,该异常会由JVM构造。
/**
* Thrown when an application attempts to use {@code null} in a
* case where an object is required. These include:
* <ul>
* <li>Calling the instance method of a {@code null} object.
* <li>Accessing or modifying the field of a {@code null} object.
* <li>Taking the length of {@code null} as if it were an array.
* <li>Accessing or modifying the slots of {@code null} as if it
* were an array.
* <li>Throwing {@code null} as if it were a {@code Throwable}
* value.
* </ul>
* <p>
* Applications should throw instances of this class to indicate
* other illegal uses of the {@code null} object.
*
* {@code NullPointerException} objects may be constructed by the
* virtual machine as if {@linkplain Throwable#Throwable(String,
* Throwable, boolean, boolean) suppression were disabled and/or the
* stack trace was not writable}.
*
* @author unascribed
* @since JDK1.0
*/
public
class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
/**
* Constructs a {@code NullPointerException} with no detail message.
*/
public NullPointerException() {
super();
}
/**
* Constructs a {@code NullPointerException} with the specified
* detail message.
*
* @param s the detail message.
*/
public NullPointerException(String s) {
super(s);
}
}