File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes NP Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NP Exception" Watch "NP Exception" New topic

NP Exception

nash avin
Ranch Hand

Joined: Nov 13, 2003
Posts: 96
I am getting a NPE in the following code at the commented line,let me know what the problem is Thanks
private void checkExit(JFrame frame) {
int i = JOptionPane.showConfirmDialog(frame,"Do you really want to exit?",
if (i == JOptionPane.YES_OPTION) {
try {
conn.close(); // This is where the exception is

} catch (Exception ex) {
} // End of if
} // End of checkExit() method
Philip Shanks
Ranch Hand

Joined: Oct 15, 2002
Posts: 189
The code within checkExit() has a scope limited to that method's code block, but which also includes variables defined at the top level of the class. A variable defined and initialized within another scope would not be available in a different scope.
The code here references an object, "conn," which is either not defined within that scope, was never properly instantiated/initialized or has been explicitly set to null, hence the NullPointerException.

Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
nash avin
Ranch Hand

Joined: Nov 13, 2003
Posts: 96
Thanks for the information,
As you have mentioned the reason for the NPE,the variable is declared as below
Connection conn = DriverManager.getConnection(url,"odbc","");
And conn.close is in CheckExit() method
How Do I go about removing the NPE.
Any help would be appreciated
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
How Do I go about removing the NPE.


Incidentally, these things should be done in the finally block, to ensure that you don't leak the resources.
[ December 06, 2003: Message edited by: Eugene Kononov ]
nash avin
Ranch Hand

Joined: Nov 13, 2003
Posts: 96
Thanks for the prompt reply.I will surely try as you suggested to put it into a finally block.
I agree. Here's the link:
subject: NP Exception
It's not a secret anymore!