I have this code snippet that I'm trying to find out what exactly it is doing, I'm pretty sure the author is pretty confused, please explain if these statements are taking any affect.
Like starting an undefined Thread what does that actually do but run in a empty thread?
What happen when class is found doesn't the return value have to be stored someway or does it load into the class in some magical way?
public SomeClass() {
try {
Class.forName("SomeclassToBeFound");
} catch (ClassNotFoundException e) {e.printStackTrace();}
new Thread().start();
}
I would appreciate some help
This is what is happening in this code snippet.
1) New thread is created which is not doing any thing. it start and ends because there no work to be done in the run method.
2) Class.forName("SomeclassToBeFound"); This line will load the class if it has not been loaded before by the class loader. But if the class is already loaded it will have no affect.
Hope this helps.
Related
If I have a try block that throws a RuntimException subclass, can a subsequent catch block catches it as an Exception? Specifically:
public class MyAppException extends RuntimeException {
// ....
}
// In some other part of the code:
try {
// Executing this results with doSomething() throwing a MyAppException.
int x = doSomething();
} catch(Exception exc) {
// Does the thrown MyAppException get caught here?
}
My thinking is yes, because a RuntimeException extends Exception. However I have some production code that is not behaving this way. So obviously, if the answer is no, then that's my answer; otherwise I need to dig down and see why my code is breaking bad. Thanks in advance!
RuntimeException is derived from Exception, so it will get caught.
Having said this, don't do it! Runtime exceptions should be prevented, not caught.
Yes. It will catch RuntimeExceptionbut in case any Exception arise in catch block that you have to catch again.
I would suggest you to make a local deployment and debug the code.
If catch(Exception) is not catching your RuntimeException then your application is not behaving the way you think.
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("Caught "+e);
}
prints
Caught java.lang.RuntimeException
Yes. It is possible to catch RuntimeExceptions.
All subclasses of Throwable can be caught.
Yes , you can catch RuntimeException...But i think its not a good approach, if you catch it you should properly manage it. Otherwise the result is out of your hand. Best way is to leave it to JVM . JVM will handle it.
Yes, your thinking is correct, I think the best way to know answer to "just writing the code", let the code tell you the answer. you can see the following simple example code:
package own;
public class MyExceptionTest {
public void testRuntimeException (){
throw new MyException();
}
public static void main(String[] args) {
try{
new MyExceptionTest().testRuntimeException();
}catch(Exception e){
System.out.println(e.getClass().getName());
}
}
}
class MyException extends RuntimeException{
public MyException(){
super();
}
}
I am a project manager in IT and I have had the same argument over and over with my devs and they simply dont care. Browsing the net, even most people advocate catching and throwing RuntimException... Every time I see it I get unbelievably furious about the inaptitude after 10 years of experience....
Rule No.1:
Never ever throw a runtimeexception in Program if you didnt catch a RuntimeException.
Rule No.2:
Only catch a Runtimeexception in order to some really import stuff that has nothing to do with your software: e.g. send a mail to operations emergency shift, log exception, restart the server....
The reason for this is that in good software there is no stacktrace in a logfile. When feel uncomfortable starting to code do this:
Create new class DevelopmentException Extends Exception.
Then goahead and write your code and catch for exception initially. Then you rethrow it as your very own developmentexception. In the method catching it you log it.
Now: Everyday grep for your very personal DevelopmentException. If you find one this means there is still work to do. Go into your code and see where the Exception came from and catch it beforehand.
Ideally you will never see a DevelopmentException in this part of your program again. Repeat until there are 0 Stacktraces in your Software left and you have perfected Exception handling.
The biggest issue with throwing and catching runtime exception is that the compile ignores it. So this means when one of your colleagues writes a booking interface and throws RuntimeException when there is a value missing (yeah, ppl really do)... ...the compiler will not show you that there might be a runtimeexception. Now, when you dont catch it then your program might just shut down without any logging.
Why is it called RuntimeException?
Many mistake this for Error during Runtime of Program, however it actually means 'An Exception so utterly destructive that the Java Runtime Environment need to be stoppep'. In other words it meand: OutOfMemory, BrokenRam, FaultyImplementation of JRE, etc... basically stuff that tell you: Program cannot run because PC is crashing....
Just my 2 cents.
Anyone experienced the same stuff?
PS: Regarding continous removal of stacktraces:
Once you see an exception try to catch it with e.g. NullpointerException.
When you see Nullpointerexception go to your code and remove the stacktrace, and just log.WARN(NullpointerOccured) and write your Program to retry or so...
Ideally you repeat until you never see a Stacktrace again.
When you cannot see a stacktrace ever it means all that could possibly go wrong is taken care of (Except for RuntimeException of course)
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.
I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the program must not stop here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file.
You're looking for the try-catch block. See, for example, this tutorial.
OutputStream os = ....;
PrintStream ps = new PrintStream(os);
while(notDone) {
try {
doStuff();
}
catch(Throwable t) {
t.printStackTrace(ps);
}
ps.print(results);
}
the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
To do all of these, it is better to surround your code with try catch block
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().