我收到了java.lang.NullPointerException,我不知道为什么。我试图使用try-catch块但它不起作用。任何人都可以解释这个块有什么问题吗?
public PriceDataAdder(Connection conn) {
try {
this.conn = conn;
statement = conn.prepareStatement("INSERT INTO `blah` (a,b,c,d,e,f,g,h,`i`,j) VALUE( ?,?,?,?,?,?,?,?,?,? )");
} catch (SQLException ex) {
Logger.getLogger(PriceDataAdder.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:6)
尝试捕捉Exception
而不是SQLException
。它将起作用,因为Exception
是所有异常的超类,并且通过捕获它,您将捕获可能在try
块内生成的所有可能异常。
无论如何,问题可能是因为conn
在调用null
时prepareStatement()
Connection
引起的,首先要确保您传递了{{1}的正确实例调用PriceDataAdder
方法的地方。
另外,请查看正在生成的日志,Logger
对象应该得到充分利用。
答案 1 :(得分:4)
您只捕获SQLException
个对象,NullPointerException
不是SQLException
的子类。您也可以插入NullPointerException|
来捕捉这些内容;见http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html。
答案 2 :(得分:2)
您应该像下面的代码一样管理您的例外
try {
this.conn = conn;
statement = conn.prepareStatement("INSERT INTO `blah` (a,b,c,d,e,f,g,h,`i`,j) VALUE( ?,?,?,?,?,?,?,?,?,? )");
} catch (SQLException ex) {
Logger.getLogger(PriceDataAdder.class.getName()).log(Level.SEVERE, null, ex);
} catch (NullPointerException ex) {
Logger.getLogger(PriceDataAdder.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(PriceDataAdder.class.getName()).log(Level.SEVERE, null, ex);
}