EDIT:
After making all the changes you suggested, the problem remained. The debugger said the lemma variable was null, but the fixes I applied didn't make things better. So, due to deadline issues, I decided to approach the problem from another view. Thank you all for your help. :)
I am writing a small program and a NullPointerException drives me crazy. I have two classes: SystemDir and Search. The first one is just an encapsulation of initial directory and a search lemma. The Search class is shown below. Briefly, I want one thread to search the first level directory and the other one to expand the subdirectories. That's where I get the exception. The exception string is
Exception in thread "Thread-0" java.lang.NullPointerException
at Search.searchFiles(Search.java:59)
at Search.<init>(Search.java:53)
at SystemDir.<init>(SystemDir.java:61)
at Search$1.run(Search.java:45)
at java.lang.Thread.run(Thread.java:679)
Where the 3 points are t.start() inside the final loop, searchFiles method call, some lines above and the new SystemDir call in the run method. Can you help me please?
public class Search {
private Thread t;
public Search(String[] subFiles, final String[] subDir, final String lemma) {
t = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<subDir.length;i++) {
try {
System.out.println(subDir[i]);
new SystemDir(subDir[i], lemma);
}
catch (NoDirectoryException ex) {
Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
searchFiles(subFiles,lemma);
}
private void searchFiles(String[] subFiles, String lemma) {
for(int i=0;i<subFiles.length;i++) {
t.start();
if(subFiles[i].contains(lemma)) {
System.out.println(subFiles[i]);
}
}
}
}
As a rule, never start a thread from a constructor. It can create all sorts of issues, which may be responsible for the exception you get.
Create the thread like you do in your constructor, make searchFiles public and call that method from the client code, not from the constructor.
Apart from that, have you checked that:
subFiles is not null
none of the subFiles[i] is null
lemma is not null
(add println statements if necessary)
and as pointed out by #Gray, you can't start a thread more than once.
You have failed to posted the source code for SystemDir, but the stack trace says that its constructor is trying to create a new Search object in addition to the one that created the thread in the first place.
More concretely, probably the new Search(...) expression somewhere in SystemDir's constructor is passing null for subFiles. Is there a call to File.list() somewhere that you haven't checked for a null return from, perhaps? Note that list() returns null if it cannot list a directory at all, due to anything from missing permissions to directory-not-found.
Also, It appears you're attempting to start the same thread object more than once. That will cause an IllegalThreadStateException if there is ever more than one element in subFiles.
You have not included all the code.
With the information provided:
in searchFiles either t, subFiles, or subFiles[i] is null.
Your code itself doesn't make much sense.
That makes it hard to spot the error.
I recommend using the Eclipse debugger, and check WHICH value is null.
As far as I can tell, your problem is within the recursion into SystemDir, where you don't provide the code of.
In your searchFiles method, what is the point of starting the thread in a loop? Do you want to run the thread on each execution of the loop? I think you are missing something here.
Check if some value that you are passing to the constructor is null.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In this answer, the code provided is:
void greet(String name) {
if (name == null) {
throw new IllegalArgumentException("Cannot greet null");
}
System.out.println("Hello, " + name);
}
I have seen similar examples on all sites where I went to learn the 'throw' keyword. What doesn't make sense to me whenever I see such examples is why would one simply not print: "Cannot greet null" instead of throwing an exception.
Questions:
Are there better examples of the utility of the throw keyword? (I am just going to pass out of high school and know only high school level Java programming so please avoid complicated examples)
In the given example, why did the user choose to throw an exception instead of simply printing the error?
Now it is time to revise the concept of Exception Handling in the Java.
First of All what is exception, whenever there is some error or say problem occur while executing the lines of code it is called the Exception.
For Example,
If a person divides something with 0, then it will give an exception as computer cannot handle the undefined entity.
Another example will be while you have declared a Scanner in order to get in integer input, but user enters an alphabet so it will also cause the exception.
Here we do exception handling, which means that we will handle exception in such a way that it will not cause program to close, those specific line which have been enclosed in the try and catch statement will not work properly but other lines will executed.
Now if we have made a method that do something lets suppose prints a line, and there is an exception occurred while printing that line, here we can do two things handle that exception at place where it has occurred or throw it.
If we handle exception at that place it is okay, and if we throw it then we have to catch it place where we have called that method.
Now as there are two types of Exceptions
1) Run Time Exception Which We Call Unchecked Exception
2) Compile Time Exception Which We Call Checked Exception
Both exceptions can be handle at the class level and method level too, one more thing we can do chain exceptional handling too. Which means that one class will throw exception to other and so on.
I think following answer can help you to understand ....
Are there better examples of the utility of the throw keyword?
Basically Throw and Throws are used to prevent the application for getting error or crashing by throwing exception.
Throws are used in the method signature and Throw are used to prevent the flow from getting error.
So here is a simple example for it.
public class Test {
// here we have used "throws" in method signature
// because we are throwing new Exception(), if array is null
public static int getValue(int[] array, int index) throws Exception {
// here we are preventing application from getting
// unconditional error (NullPointer exception)
// if array is null, then we are throwing new Exception()
if(array == null) {
throw new Exception();
}
int value = array[index];
return value;
}
public static void main(String[] args) {
int[] array = null;
// here we are wrapping our getValue() function call to try catch block
// because getValue() function can throws Exception
// so we are making it safe to execute our program
try {
int value = getValue(array, 0);
System.out.println("value " + value);
} catch (Exception e) {
System.out.println("Provided array is null... so we caught the exception...");
}
}
}
if you want to know more about how throw and throws works... then you need to know about Exception Handling (Checked and Unchecked) also.
In the given example, why did the user choose to throw an exception instead of simply printing the error?
As per the given example, your function purpose is to greet, but if some other function call greet() with
null value then there is no any reason to greet like Hello, null, so he throw an exception before executing the statement. like...
void greet(String name) {
System.out.println("Hello, " + name);
}
String myName = null;
greet(myName); // it will print "Hello, null";
'Throw' keyword is used to notify the caller that the argument passed is not valid (in this case), or in general, something went wrong while executing the code called by the caller.
Consider an example where you are writing an online shopping application. Following would be the simple sequence of events:
User scrolls through items and selects one or more items
Items are added into the cart and user clicks check out
User is redirected to 3rd party's payment page where he types in card details and makes the payment
User is shown the success page
Now, during payment, if the card number is incorrect or user doesn't have enough balance in the card, would you throw the error back to the caller (i.e. shopping app) or just log it on the console (on payment provider's side) and return the response? Of course the former, so this is just to let the caller know that there is an error and he should handle it gracefully (by showing appropriate message on checkout in our case).
A throw statement abruptly terminates the execution of the current function, and returns control right back to the caller, forcing them to deal with the error, or rethrow the exception up the chain.
An exception object contains lots of information about where and why an error occurred beyond just the error message. It keeps track of where in the call stack the error happened, and allows you to look up the sequence of calls that led up to it.
A print statement simply could not do all these things. Your example is already a good one. The job of the greet function is to print a greeting. If you pass in null, the function is unable to do so. Printing a message here would be potentially confusing. Instead, it forces you to deal with the fact that you have it invalid input rather than printing a benign message that someone might mistake for a greeting.
Try Java 8 Optional:
String nullVal = null;
System.out.println(Optional.ofNullable(nullVal).orElseGet(() -> null));
String notNull = "Hello Optional";
System.out.println(Optional.ofNullable(notNull).orElseGet(() -> null));
The method can be modify like this:
public static void greet(String name) {
System.out.println("Hello, " + Optional.ofNullable(name).orElseGet(()->null));
}
Assume a function checks that in the passed directory is no malicious file. That could be a void method where you need to catch the exception for the rare case, bypassing the normal processing after the call.
try {
checkDirectorySafe("/home/Donald");
...
} catch (VirusException e) {
...
}
The catch might be late in the code and also catch exceptions in other parts.
There is an other advantage. The function can check all files in the directory and for all subdirectories need only recursively call itself with the subdirectory path. On an exception the call stack is unwound upto the catch.
The Alternative would be to have a boolean or Optional result, and add if code. If the function also needs to return some data, that could become slightly uglier.
An exception is like a toilet in a mall.
I have read through the JEditorPane Docs, from what I can understand you simply need to editorpane.setText(String value); however I am quite new to java and this solution does not work with my code. I think I am missing something obvious but completely out of ideas.
I have created a new tab with this class that extends JEditorPane, this class is designed to open the contents of the file, put them on an array, reverse the array (so latest entry is on the top) then display this list in the JEditorPane (using JeditorPane because I need to make the save url's into hyperlinks),
public class HistoryPane extends JEditorPane{
ArrayList<String> historyToSort = new ArrayList<String>();
public HistoryPane(){
setEditable(false);
historySort();
}
public void historySort() {
try (BufferedReader reader = new BufferedReader(new FileReader("BrowserHistory.txt")))
{
String currentLine;
String newLine = new String("\n");
while ((currentLine = reader.readLine()) != null) {
historyToSort.add(currentLine + newLine);
}
} catch (IOException e) {
e.printStackTrace();
}
Collections.reverse(historyToSort);
System.out.println(historyToSort);
}
{
}
private void displayHistory(){
String sorted = historyToSort.toString();
***** HistoryPane.setText(String sorted); <<<------ PROBLEM SYNTAX.*****
}
}
I have tried multiple different entries into the setText() parenthesis with no luck. What am I missing? Thank You.
NOTE:
This class won't compile because it is reliant on another class (I can't paste all of it) but this code sits within a tabbed pane created by my main class:
Error Message:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
Syntax error on token "setText", Identifier expected after this token
Return type for the method is missing
This method requires a body instead of a semicolon
OK, despite the fact that you haven't read the error message, it seems you're really a newbie, so I'll help.
HistoryPane.setText(String sorted);
The above isn't valid Java. A method invocation takes a list of arguments, without a type.
HistoryPane.setText(sorted);
Now that is a valid method invocation. But it tries to invoke a static method called setText() of the class HistoryPane. What you want is to invoke the instance method setText() on the current object. So the valid syntax is
this.setText(sorted);
or simply
setText(sorted);
That should solve this particular compilation error. Don't try to run your app before every compilation error, listed in the Problems view of Eclipse, is fixed.
Note that the above line won't do what you want it to do, but I'll let you investigate what you should do instead.
My advice: don't try using Swing, which is quite a complex beast, if you don't even know how to call a method yet. Start with very simple Java exercises, not involving any GUI, until you're familiar with the Java syntax, and understand how to read, understand and fix basic compilation problems.
I am writing a blackberry app that communicates with a simple Bluetooth peripheral using text based AT commands - similar to a modem... I can only get it working on the blackberry using an event listener. So the communication is now asynchronous.
However, since it is a simple device and I need to control concurrent access, I would prefer to just have a blocking call.
I have the following code which tries to convert the communications to blocking by using a wait/notify. But when I run it, notifyResults never runs until getStringValue completes. i.e. it will always timeout no matter what the delay.
The btCon object runs on a separate thread already.
I'm sure I am missing something obvious with threading. Could someone kindly point it out?
Thanks
I should also add the the notifyAll blows up with an IllegalMonitorStateException.
I previously tried it with a simple boolean flag and a wait loop. But the same problem existed. notifyResult never runs until after getStringValue completes.
public class BTCommand implements ResultListener{
String cmd;
private BluetoothClient btCon;
private String result;
public BTCommand (String cmd){
this.cmd=cmd;
btCon = BluetoothClient.getInstance();
btCon.addListener(this);
System.out.println("[BTCL] BTCommand init");
}
public String getStringValue(){
result = "TIMEOUT";
btCon.sendCommand(cmd);
System.out.println("[BTCL] BTCommand getStringValue sent and waiting");
synchronized (result){
try {
result.wait(5000);
} catch (InterruptedException e) {
System.out.println("[BTCL] BTCommand getStringValue interrupted");
}
}//sync
System.out.println("[BTCL] BTCommand getStringValue result="+result);
return result;
}
public void notifyResults(String cmd) {
if(cmd.equalsIgnoreCase(this.cmd)){
synchronized(result){
result = btCon.getHash(cmd);
System.out.println("[BTCL] BTCommand resultReady: "+cmd+"="+result);
result.notifyAll();
}//sync
}
}
}
Since both notifyResults and getStringValue have synchronized clauses on the same object, assuming getStringValues gets to the synchronized section first notifyResults will block at the start of the synchronized clause until getStringValues exits the synchronized area. If I understand, this is the behaviour you're seeing.
Nicholas' advice is probably good, but you may not find any of those implementations in BlackBerry APIs you're using. You may want to have a look at the produce-consumer pattern.
It may be more appropriate to use a Latch, Semaphore, or a Barrier, as recommended by Brian Goetz book Java Concurrency in Practice.
These classes will make it easier to write blocking methods, and will likely help to prevent bugs, especially if you are unfamiliar with wait() and notifyAll(). (I am not suggesting that YOU are unfamiliar, it is just a note for others...)
The code will work ok. If you will use final object instead of string variable. I'm surprised that you don't get NPE or IMSE.
Create field:
private final Object resultLock = new Object();
Change all synchronized sections to use it instead of string field result.
I don't like magic number 5 sec. I hope you treat null result as timeout in your application.
This code has lot of trouble for my AIR 2.0 Native process which I tried to launch Java from AIR application, then the Java.exe terminate itself in the Windows Task manager, I found that new MidiTest() was the caused. Is there a better solution for new instance?
public static void main(String[] arg) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!(speed.equals(speed_stop))) {
try {
speed = in.readLine();
if(!(Global.newPlayer.equals("1"))){new MidiTest();}
} catch (IOException e) {
System.err.println("Exception while reading the input. " + e);
}
}
}
private MidiPlayer player;
public MidiTest() {
System.out.println("Start player");
// /*
}
There is no alternative to new.
This is the only way to instantiate an object. Even if you use reflection, you're still calling the constructor. You need to track down the problem. Find the exact exception that's being caused, and the exact line number, and then see what you need to do to fix that problem.
I can see that you didn't provide a complete copy of your code. There's an open comment before the close brace, and it's not right. So that means we can't help you any further with the information we have.
No, the only other option for creating a new instance of your class would be using reflection, which is a much more obscure and error prone choice than new. It should not be used unless one really needs to. And even that is loading the class and calling the object's constructor in the end, exactly the same way as new.
I suspect the problem lies somewhere in code you haven't shown to us. Does MidiTest have any (static or nonstatic) initializer blocks? Is that println() statement really the only code in its constructor?
Of course, it helped if you traced down what is the exact error/exception causing the termination and where exactly does it originate from :-)
ANSWER:
If you ever see these lines and are mistified like I was, here's what they mean.
Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))
EventDispatchTread.run() line: not available [local variables unavailable]
It's not that the variables are unavailable because they are lurking behind a shroud of mystery in a library somewhere dank. No no, they just went out of scope! It's still your fault, you still have to find the null, and no you can't blame the library. Important lesson!
QUESTION:
One of the most frustrating things for me, as a beginner is libraries! It's a love/hate relationship: On the one hand they let me do things I wouldn't normally understand how to do with the code that I do understand, on the other hand because I don't completely understand them, they sometimes throw a wrench in code that is otherwise working fine! It's because I don't understand the errors that can occur when using these libraries, because I didn't write them, and because eclipse doesn't give me a great deal to go with when one of imports starts acting up...
So here's the problem: I've been working with java.awt.event to handle a bunch of JButtons on the screen for this and that. I get an error when I use one of the buttons I've made. The error is:
Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))
EventDispatchTread.run() line: not available [local variables unavailable]
What does this mean? What could be causing it? I'm embarrassed to post code, but if you can stand to try to decipher my terrible style, here is the method that seems to cause this error to be thrown.
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String name;
code...
if(cmd.equals("Play")) {
name = field.getText();
card = getCard(name);
if(card != null) {
if(rules.zoneHasCard(card, rules.hand)) {
display.updateStatusMessage(rules.play(card));
field.setText("");
display.updateHand(rules.zoneList("hand"));
display.updateDiscard(rules.zoneList("Discard")); // This is the error here! The discard Zone was empty!
}
else {
field.setText("You do not have " + card.getName());
field.selectAll();
}
}
else {
field.setText("That cardname is unused");
field.selectAll();
}
}
}
Welcome to the complexity of writing GUI code.
When you run a Swing program, a background thread called the Event Dispatch Thread is created. When the user clicks on a JButton, for example, JButton creates and fires an event using this Event Dispatch Thread. Hence the name: it's the thread that dispatches events!
Your code:
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String name;
// more code...
}
is called by this Event Dispatch Thread, so your code can handle the event.
Somewhere within your code you are trying to do something with a variable that is currently equal to null. The error message is telling you, "hey while running some code on the event dispatch thread, I encountered a NullPointerException" in your code.
Why are you not receiving more info? Possibly you configured Eclipse not to include debug info when compiling?
For now, I recommend adding some lines to your actionPerformed method to show the state of variables:
System.out.println("field = " + field);
System.out.println("rules = " + rules);
System.out.println("display = " + display);
See if this shows you any nulls.
Even if the NullPointerException comes from a library, the stack trace will show which line of your code called that library. But only if you've configured Eclipse to generate debugging info.
In the longer term, work through the Sun's Swing Tutorial to learn more about these issues.
Any method call on a null object will raise a null pointer exception.
In your code, rules, name or display could be null and cause an exception.
Use a debugger (such as the one included in the eclipse IDE) and set a breakpoint at the start of the actionPerformed() method, then step through it line by line to see when a variable you try to invoke a method on is null.
Just don't stop reading the stack trace after two lines. Somewhere in the stack trace you'll recognise the name of one of the classes/methods which you did write. Start looking there. (btw, people spend way to much time inside debuggers :-))
You might have forgotten to actually set an ActionCommand.
In the ActionEvent API Doc there's a note regarding possible null results of getActionCommand().