NullPointerException without referencing any object - java

I have a piece of code, that throws NullPointerException sometimes. So far not really interesting. But the Exception occurs in a line, that does not reference any object.
try
{
parser.parse(input);/*line 186*/
}
catch(Exception e)
{
//NPE happens in the next line?
throw new SAXException("Error parsing document", e);/*line 190*/
}
Here the Stacktrace
java.lang.NullPointerException
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:190)
at com.tejoe.MyXMLParser.parse(MyXMLParser.java:168)
....
It happened only twice in the last three months and the code run at least a hundred thousand times.
I already decompiled my code, to make sure the line information were correct and yes they are.
Additional Test
There seems to be something special with SAXException. I did the following test:
import org.xml.sax.SAXException;
public class Test
{
public static void main(String[] args) throws Exception
{
new SAXException("Error", new NullPointerException()).printStackTrace();
}
}
I got the following output
java.lang.NullPointerException
at Test.main(Test.java:7)
Caused by: java.lang.NullPointerException
... 1 more
Solution:
SAXException overrides toString method, to return the Name of the cause Exception.
Now I only wonder, that I did not get the caused by output in the production environment (AIX JAVA)

I wrote following code and generated null pointer exception. It came on line 45 as follow,
Exception in thread "main" java.lang.NullPointerException
at inheritance.parent.Child.main(Child.java:45)
import org.xml.sax.SAXException;
public class Child {
public static void main(String[] args) throws SAXException {
try{
Child c1 = null;
c1.i=0;
} catch(Exception e){
throw new SAXException("Error", e); //Line : 45
}
}
}
The error for your code is proper. You need to find which object you are getting null.

Your code must have changed since you made your last release. This will mess up the line numbers, since they are based on the code at the time it was compiled.
It looks like you've removed some code from that file since the release, meaning that the line numbers are larger than they should be.

Replace your line :
throw new SAXException("Error parsing document", e);
with
e.printStackTrace();
you will find the right error line.

Related

Error with java FileInputStream and FileOutputStream

I just made my first I/O based stuff in Java.
I want to check if the content written to a file is properly saved in, or not.
For which i wrote the following code..
import java.io.*;
public class check implements Serializable {
//Make two variables and methods to initialise them
private int height;
private int width;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
public static void main(String[] args) {
check obj = new check();
obj.setHeight(20);
obj.setWidth(30);
try{
FileOutputStream fs = new FileOutputStream("foo.txt");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(obj);
os.close();
}
catch(IOException ex){
}
//We set them to null so we can't access the objects on heap.
obj = null;
//Now we read them back from file
try{
ObjectInputStream is = new ObjectInputStream(new FileInputStream("foo.txt"));
check stored = (check) is.readObject();
//Check to see if it worked.
System.out.println("Variable, stored contains.." + stored.getType());
}
catch(IOException ex){
}
}
}
But it produces the following error.
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
at check.Check.main(Check.java:33)
Anyone got any idea to solve the issue?
Take a look at http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readObject(). The method lists a couple of exceptions. For every exception listed that is not a sub-class of RuntimeException you need to either catch the exception or declare that the method can throw that exception. You have only done this for IOException. You also need to do this for the other exceptions listed in the documentation. This needs to be done for all methods that throw non-runtime exceptions.
Your IDE is letting you run some code even though you are missing some classes or despite having compilation errors. Fix the compilation errors before you run them.
Your code is uncompilable at the moment. Line 36 fails.
System.out.println("Variable, stored contains.." + stored.getType());
This is because the class check does not contain a method getType(). Maybe You meant something along the lines of getClass().getName()?
Fix this error and try again. Your own error message does not make sense to me - is it generated by an IDE?
PS. Have a look at Java coding conventions regarding the naming of classes, variables and such. :)

File Layout Exception

I'm writing a java Application that can open and edit files. But I want it to give me an error if the layout of the file isnt as it should be.
My file looks like this:
Title
X Y
Name
X times line
If looked into try and catch but that doesnt give me the right solution to give an error like:
"There is no X or Y specified"
or
"There is nog Title in this file"
Whats the option to do this?
Create your own Exception class that extends Exception. This is sometimes called a domain exception, because it's one that only applies to your problem domain.
Here's an example of how you would code it:
public class FileLayoutException extends Exception {
// extending Exception means you can throw it and declare it to be thrown
}
Declare your method to throw it:
public void readFile() throws FileLayoutException {
// some impl
}
Then use it like this when you detect a problem:
throw new FileLayoutException("There is no X or Y specified");
or
throw new FileLayoutException("There is no Title in this file");
Because your error conditions are "file-related", you may consider extending IOException instead of Exception

FileNotFoundException when creating a Scanner in Eclipse with Java

I'm getting a FileNotFoundException when running the following Java 6 code on Eclipse (Indigo) on Snow Leopard:
import java.io.*;
import java.util.*;
public class readFile {
public static void main(String[] args) {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
}
The exception is
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at readFile.main(readFile.java:9)
My current workspace is /Users/daniel/pr/java. It contains only one project (readFile), and the file hierarchy looks like this:
- readFile
- src
- (default package)
- readFile.java
- JRE System Library [JavaSE-1.6]
- myfile.txt
After reading several very similar questions, I've tried
placing copies of myfile.txt in the project, bin, src, and workspace directories, as well as my home and root folders
identifying the working directory and using a relative path
manually setting the workspace via "Run Configurations > Arguments > Working Directory" in Eclipse
running the program with the command line Java launcher in the bin, readFile, src, and java directories (with copies of myfile.txt in all of these places)
removing the file extension and/or lengthening the filename (above some supposed minimum character limit), and
verifying the permissions of myfile.txt (they're now rw-r--r--).
I'm at a loss. What could be the problem? (Thank you for reading!)
The exception tells you the problem.
The code you have in your main might throw a FileNotFoundException, so you need to consider that in your code, either by declaring in the method signature that that exception can be thrown, or by surrounding the code with a try catch:
Declaring:
public static void main(String[] args) throws FileNotFoundException{
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
Or using try/catch
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch (FileNotFoundException e) {
//do something with e, or handle this case
}
}
The difference between these two approaches is that, since this is your main, if you declare it in the method signature, your program will throw the Exception and stop, giving you the stack trace.
If you use try/catch, you can handle this situation, either by logging the error, trying again, etc.
You might want to give a look at:
http://docs.oracle.com/javase/tutorial/essential/exceptions/ to learn about exception handling in Java, it'll be quite useful.
FileNotFoundException is a checked exception ! You must catch the exception ...
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch(FileNotFoundException ex) {
//Handle exception code ...
}
}
"/Users/daniel/pr/java/readFile/myfile.txt"
Shouldn't that be:
"/users/daniel/pr/java/readFile/myfile.txt"

How to show full stack trace on eclipse?

I'm using Eclipse to debug a Java application. Somewhere in the code I get an exception and the stack trace:
Caused by: java.io.EOFException: The connection has been reset while reading the header
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.fetchHeader(Message.java:583)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.readHeaderAndPayload(Message.java:599)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.read(Message.java:542)
at com.gemstone.gemfire.internal.cache.tier.sockets.Message.recv(Message.java:1029)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:158)
at com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363)
at com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229)
at com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646)
at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108)
... 11 more
How do I get the whole stack instead of the ... 11 more?
You have the entire stack.
This is only part of a stack trace. Directly before this was another piece. Look at the bottom lines of this one, and the top lines of the previous one. You'll see them match up. The stack trace began with a section that doesn't begin with "Caused by".
The "Caused by" exception is hiding parts of the stack trace that are verbatim copies of stack trace entries in its parent. In other words, Java doesn't show the entire stack up to main() for every cause - it just shows what you haven't seen already. See the Throwable.printStackTrace() documentation.
The "Caused by" is filled when you provide a cause when creating a Throwable. Look at the constructors for it. This is done when a piece of code catches a low-level exception and then wants to rethrow it as a different exception class.
the answers above are not accurate, every time the stack show the words "caused by" it means that the exception went through one or multiple methods until it was caught, and then thrown again. This could happen many many many times, the stack trace is not a loop, it is a single direction, so no, the stuff at the top does not relate to the stuff at the bottom, the most important part IS at the bottom, that is the root of the exception, so if you would have:
Exception in class main: blah blah blah
...lines of code...
caused by FileNotFoundException
...lines of code...
caused by: MalformedURLException
...lines of code...
caused by: NullPointerException
then you would not want to focus so much on the FileNotFoundException, but you would want to focus more on the NullPointerException. Like say you had a properties file with a file name in it. If accidentally used mykey, to find the property "myKey", then the propertiesResource would return a null, that would then get thrown all the way through all the lines of code (hopefully) to your application where the last catch block is. . . wich, at this piont, it would be "wrapped" not as a nullException, but as a FileNotFoundException. . .
We might be diverging from the actual problem he's facing. I was having similar problem and it turns out I had my Limit console out put box check marked. After I removed it I was able to see the full stack trace.
Steps:
Right click on console || ctrl + click if mac
go to preferences and follow the above instructions
I think it means that the Exception was caught and packaged into another 11 times before printStackTrace was called.
Try and figure out the output of the following program for better understanding:
public class PrintStackTrace {
public static void main(String[] args) {
try {
level1();
} catch (Exception e) {
e.printStackTrace();
}
try {
level2();
} catch (Exception e) {
e.printStackTrace();
}
}
static void level2() throws Exception {
try {
level1();
} catch (Exception e) {
throw new Exception(e);
}
}
static void level1() throws Exception {
try {
throwingMethod();
} catch (Exception e) {
throw new Exception(e);
}
}
static void throwingMethod() throws Exception {
throw new Exception("throwingMethod");
}
}
As Ed says, it is showing the entire stack, but leaving out information that you've already seen. See Throwable#printStackTrace()
Quoting from there:
Note the presence of lines containing the characters "...". These
lines indicate that the remainder of the stack trace for this
exception matches the indicated number of frames from the bottom of
the stack trace of the exception that was caused by this exception
(the "enclosing" exception). This shorthand can greatly reduce the
length of the output in the common case where a wrapped exception is
thrown from same method as the "causative exception" is caught
Often an exception is wrapped; created with another exception as the cause:
try {
// something which causes an Exception
} catch (Exception e) {
throw new SpecificException("help", e);
}
In this case, displaying the stacktrace will create the ... 11 more that you see.
I have never seen that, but try this
public void problemFunction(){
try{
//your code
catch(Exception ex){
ex.printStackTrace();
}
}
or
public void problemFunction(){
try{
//your code
}
catch(Exception ex){
System.out.println(ex);
StackTraceElement[] arr = ex.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
}
}
There is a vmargs option
-XX:-OmitStackTraceInFastThrow
which might help in some situations.
To simplify the accepted answer let us consider a simple notation.
Exception in main ……
At A
At B
At C
Caused by ….
AT P
At Q
AT R
AT A - > { THIS ONE IS REPEATED , But slightly with line
number changes } .
MISSING 2 MORE { THOSE 2 ARE NOTHING BUT B AND C .}
Caused by …
At X
At Y
At P - > { THIS ONE IS REPEATED , But slightly line
number changes }
Missing 5 More ( Those 5 are nothing but Q,R, ,A,B,C )
Hence you have the entire stack.
But MAKE SURE CHECK BOX FOR “limit console output” is NOT checked under run/debug drop down --> console in eclipse preferences.
You can use the following code to get more clarity.
try {
// code causing exception
}
catch(Exception ex){
Throwable exThrowable=ex;
while(exThrowable!=null) {
System.out.println(exThrowable);
StackTraceElement[] arr =
exThrowable.getStackTrace();
for(int i=0; i<arr.length; i++){
System.out.println(arr[i].toString());
}
exThrowable=exThrowable.getCause();
}

Exception Handling in java error in the following code

import java.io.*;
public class Mainclassexec
{
public static void main(String[] args)
{
String input = null;
try
{
String capitalized = capitalize(input);
System.out.println(capitalized);
} catch (NullPointerException e)
{
System.out.println(e.toString());
}
}
public static String capitalize(String s) throws NullPointerException
{
System.out.println("Enter a string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine(); //--->error here IOException must be caught
// or declared to be thrown
if (s == null)
{
throw new NullPointerException("You have passed a null argument");
}
Character firstChar = s.charAt(0);
String theRest = s.substring(1);
return firstChar.toString().toUpperCase() + theRest;
}
}
How should i clear this error? Also, please suggest me some links on learning exception handling. I am very confused with this topic.
Here you go,
public class Mainclassexec {
public static void main(String[] args) {
String input = null;
try {
String capitalized = capitalize(input);
System.out.println(capitalized);
} catch (IOException e) {
System.out.println(e.toString());
}
}
public static String capitalize(String s) throws IOException {
System.out.println("Enter a string");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
Character firstChar = s.charAt(0);
String theRest = s.substring(1);
return firstChar.toString().toUpperCase() + theRest;
}
}
One advice, NullPointerException is a RuntimeException. You don't have to throw it explicitly. The best practice is to handle Nullpointers wherever possible instead of throwing it. It makes the code nasty and it has no added value during compile time.
You can refer this link for a detailed tutorial on Exception handling in Java.
Add "IOException" to the list of exceptions that the capitalize method throws
i.e.
public static String capitalize(String s) throws NullPointerException, IOException
...
This way it tells any piece of code calling the capiatlize method that it must be able to handle both types of exception.
EXception tutorials
http://www.javabeginner.com/learn-java/understanding-java-exceptions
http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html
http://www.sap-img.com/java/java-exception-handling.htm
BufferedReader.readLine() is a method that throws IOException, meaning your program should handle that error itself. It is written that way so that you can do any measure that you need (e.g. to make it clear to the user that the string entered is null, which is the best practice on java and not try to catch the value using s==null).
Add IOException to the throws clause. You can also use just Exception. You can also use try-catch to handle the IOException differently - consume it (not recommended) or throw some other Exception.
The NullPointerException is non checked, so you don't need to add to the throws clause.
#Bragboy's answer is enough to fix the compilation error and get the program working. The problem that this fixes is that the BufferedReader.readLine() method can throw IOException, and that is a checked exception. Java insists that when a checked exception is thrown within a method (or some other method that the method calls), it must EITHER be caught in the method using a try / catch OR declared as thrown by the method. #Bragboy's answer does the latter in the capitalize, and then catches the IOException in the main method.
However, there are other important issue too.
Currently capitalize does not do what the method name and signature clearly implies. The signature implies that the method capitalizes its argument. In fact, it totally ignores its argument and reads (and capitalizes) a String from stand input instead.
A better design would be to read the input String into input in the main method, and pass it as the s argument. Then change capitalize to just capitalize the argument String.
Two other points of style:
The class name should be MainClassExec ... not Mainclassexec; refer to the Java Style Guide for an explanation of the Java naming conventions.
The way that your application is dealing with missing input is ugly. Assuming that you've fixed capitalize as I suggested, then the main method should test that the input variable is not null before calling capitalize.
Finally, in my opinion, there is rarely any point doing something like this:
if (x == null) {
throw new NullPointerException(...);
}
x.something();
Instead you should simply do this:
x.something();
This will automatically throw an NullPointerException if x is null. Besides, it is a bad idea to use the message of NullPointerException to contain a user error message. Most NPEs happen as a result of programming errors somewhere. If you start using NPEs to report errors resulting from (for example) bad input from the user, you'll end up with a mess.

Categories

Resources