[英]try-catch block not suppressing java.lang.NullPointerException
I am getting the java.lang.NullPointerException and i am not sure why. 我收到java.lang.NullPointerException,我不知道为什么。 I am trying to use a try-catch block but it does not work. 我试图使用try-catch块但它不起作用。 Can anyone explain what is wrong with this block? 任何人都可以解释这个块有什么问题吗?
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);
}
}
Try catching Exception
instead of SQLException
. 尝试捕获Exception
而不是SQLException
。 It will work because Exception
is the superclass of all exceptions, and by catching it you're catching all possible exceptions that might get generated inside the try
block. 它将起作用,因为Exception
是所有异常的超类,并且通过捕获它,您将捕获可能在try
块内生成的所有可能的异常。
Anyway, the problem is probably caused because conn
is null
at the point where prepareStatement()
is called, start by making sure that you're passing a correct instance of Connection
where the PriceDataAdder
method is called. 无论如何,问题可能是因为在调用prepareStatement()
conn
为null
,首先要确保在调用PriceDataAdder
方法时传递正确的Connection
实例。
Also take a look at the log that's being generated, that Logger
object should be put to good use. 另外,请查看正在生成的日志,应该充分利用Logger
对象。
You are only catching SQLException
objects, and NullPointerException
is not a subclass of SQLException
. 您只捕获SQLException
对象, NullPointerException
不是SQLException
的子类。 You can insert NullPointerException|
您可以插入NullPointerException|
to catch those also; 抓住那些; see http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html . 请参阅http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html 。
You should manage your exception like the below code 您应该像下面的代码一样管理您的异常
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.