I'm trying to handle an FileNotFoundException in Java by suspending the thread for x seconds and rereading the file. The idea behind this is to edit properties during runtime.
The problem is that the programm simply terminates. Any idea how to realize this solution?
There's a good-old recipe, originally by Bjarne Stroustroup for C++, ported here to Java:
Result tryOpenFile(File f) {
while (true) {
try {
// try to open the file
return result; // or break
} catch (FileNotFoundException e) {
// try to recover, wait, whatever
}
}
}
Do the file loading in a loop and set the variable the condition depends on after the file has been successfully read. Use a try-catch block inside the loop and do the waiting in the catch-block.
Some code snippets would be useful, but one of the following could be the problem:
Your code successfully catches the first FileNotFoundException but after waking up the code does not successfully handle a second one
Another exception is being thrown which is not being handled. Try temporarily wrapping the code in question with a catch (Exception e) to see what exception is being thrown
The program you use to edit the file is 'locking' the properties file and possbily preventing access by your Java code.
Good luck
If the Exception is never caught, the thread is terminated. If this is your main thread, the application ends. Try the following:
try
{
props.load(...);
}
catch (FileNotFoundException ex)
{
Thread.sleep(x * 1000);
props.load(...);
}
Related
This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
While learning Java I stumble upon this error quite often. It goes like this:
Unreported exception java.io.FileNotFound exception; must be caught or declared to be thrown.
java.io.FileNotFound is just an example, I've seen many different ones. In this particular case, code causing the error is:
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("myfile.pdf")));
Error always disappears and code compiles & runs successfully once I put the statement inside try/catch block. Sometimes it's good enough for me, but sometimes not.
First, examples I'm learning from do not always use try/catch and should work nevertheless, apparently.
Whats more important, sometimes when I put whole code inside try/catch it cannot work at all. E.g. in this particular case I need to out.close(); in finally{ } block; but if the statement above itself is inside the try{ }, finally{} doesnt "see" out and thus cannot close it.
My first idea was to import java.io.FileNotFound; or another relevant exception, but it didnt help.
What you're referring to are checked exceptions, meaning they must be declared or handled. The standard construct for dealing with files in Java looks something like this:
InputStream in = null;
try {
in = new InputStream(...);
// do stuff
} catch (IOException e) {
// do whatever
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
Is it ugly? Sure. Is it verbose? Sure. Java 7 will make it a little better with ARM blocks but until then you're stuck with the above.
You can also let the caller handle exceptions:
public void doStuff() throws IOException {
InputStream in = new InputStream(...);
// do stuff
in.close();
}
although even then the close() should probably be wrapped in a finally block.
But the above function declaration says that this method can throw an IOException. Since that's a checked exception the caller of this function will need to catch it (or declare it so its caller can deal with it and so on).
Java's checked exceptions make programmers address issues like this. (That's a good thing in my opinion, even if sweeping bugs under the carpet is easier.)
You should take some appropriate action if a failure occurs. Typically the handling should be at a different layer from where the exception was thrown.
Resource should be handled correctly, which takes the form:
acquire();
try {
use();
} finally {
release();
}
Never put the acquire() within the try block. Never put anything between the acquire() and try (other than a simple assign). Do not attempt to release multiple resources in a single finally block.
So, we have two different issues. Unfortunately the Java syntax mixes up the two. The correct way to write such code is:
try {
final FileOutputStream rawOut = new FileOutputStream(file);
try {
OutputStream out = new BufferedOutputStream(rawOut);
...
out.flush();
} finally {
rawOut.close();
}
} catch (FileNotFoundException exc) {
...do something not being able to create file...
} catch (IOException exc) {
...handle create file but borked - oops...
}
I need my application to bring up an error in writing to the location /dev/full. Is there anyway I can do this with Java exception handling? I am already throwing and catching IOerrors, so I don't know what the problem is...?
I am reading data from standard in, and compressing it and writing it to standard out.
Writing to /dev/full isn't raising an exception...any ideas on how to raise an exception for this?
There is a Parent Class for all Exceptions that is Exception. If you are not sure which type of exceptions are thrown from try block, use Exception in your last catch block.
something like this
try{
....//code here
}
catch(FileNotFoundException fnfe){
log(fnfe);
}
catch(IOException ioe){
log(ioe);
}
catch(Exception e){
log(e);
}
finally{
....//code here
}
You could write a code for writing all the details of the error and any specific comments you wish to make regarding the class or object so that you can trace the error better inside the catch block.
try
{
//Your code
}
catch(SomeException e)
{
//Create a file, write data to it and close it.
}
I use this technique to save user data in case a file cannot be opened for modifications. Helps because i am sure that the data will be stored at either of the 2 places.
Also, this doesn't affect my further executing of the program as the data is loaded in an object of File. There could be better methods to the above. But this is what my professor showed me. Could be of use.
I think on the following examples; but could not figure out what the importance of the finally block is. Can you tell me the difference of the executions of these two code samples? Also a real life example can be helpful.
Sample 1:
try{
// some code 1
}catch(Exception ex){
// print exception
}finally{
// some code 2
}
Sample 2:
try{
// some code 1
}catch(Exception ex){
// print exception
}
// some code 2
There is a big difference in the two snippets you've presented, e.g. when the catch block itself throws an exception, the finally block would still be executed by its semantics.
That is the following snippet prints "Finally!", but not "What about me???":
try {
throw null; // throws NullPointerException!
} catch (Exception e) {
int oops = 1/0; // throws ArithmeticException!
} finally {
System.out.println("Finally!"); // still gets executed!
}
System.out.println("What about me???"); // doesn't get executed!
Generally speaking, the finally of a try block practically always gets executed. There's no such guarantee for any code following the try block.
But what if my catch block is just a simple print statement?
There's still no guarantee that it won't throw something. Something could still go wrong in e.g. the construction for the exception detailed message.
Even if you make a best effort guarantee that the catch code is "safe" and the code following the try statement will always be executed, the question then becomes "Why?". Why avoid finally but then try so hard to replicate its semantics?
finally semantics is guaranteed, requiring no burden of proof from either the writer or the reader of the code. Precisely because of this, it's idiomatic to use finally block to put mandatory "clean-up" code. Using finally guarantees correctness and enhance both writability and readability.
The finally block is executed even if e.g. an Error is thrown, which is not caught by the catch block in your example. So you can put cleanup code in the finally block, which should be run always, regardless of the outcome of the operations in the try and catch blocks.
Note that usually catch blocks catch more specific types of exceptions - often only checked exceptions -, so in most cases the difference between the two code examples above is very definite.
Update: you may say that your catch block can never throw an exception, so finally is not needed. However, note two things:
this is only the current state of the code, and it can change in the future - can you guarantee that the future programmer who adds some potentially exception-throwing code in the catch block, will remember to put the cleanup code after it into a finally block?
try-catch-finally is a programming idiom which makes it easier for people reading the code to understand what's going on. If you don't use the common idiom, you risk misunderstanding, thus bugs on the long term.
You use the finally block in order to cleanup and run any code that should run whether an exception was thrown (and caught) or not. This includes code that you have in the catch block.
it is helpful when we want to free up the resources we used in try block. So the only place to execute them without missing at any case is finally block. Since if exception is thrown, java does not execute code which immediate after that. it directly jump to the catch block.
Note that you can have even try-finally without a catch:
try{
// some code
}finally{
// cleanup code
}
An example therefore could be a method that wants to propagate exceptions to the caller, but still needs clean up code, like releasing a look.
In case where the statements in try block throw unchecked exceptions, finally block will get executed allowing programmer to take relevant actions.
In real life, the finally block is used to close opened resources even if an exception occurs.
For example, when you read (or write) a file, when you access to a database, etc.
public void readFile(String fileName) {
FileReader fr;
BufferedFileReader bfr;
try {
fr = new FileReader(fileName);
bfr = new BufferedFileReader(fr);
// ...
} catch (IOException ioe) {
// ...
} finally {
// TO ENSURE THAT THE READERS ARE CLOSED IN ALL CASES
if (bfr != null) {
try {
bfr.close();
} catch (IOException ignoredIOE) {}
}
if (fr != null) {
try {
fr.close();
} catch (IOException ignoredIOE) {}
}
}
}
What does try do in java?
try is used for exception handling.
http://java.sun.com/docs/books/tutorial/essential/exceptions/try.html
The try/catch/finally construct allows you to specify code that will run in case an exception has occured inside of the try block (catch), and/or code that will run after the try block, even if an exception has occured (finally).
try{
// some code that could throw MyException;
}
catch (MyException e){
// this will be called when MyException has occured
}
catch (Exception e){
// this will be called if another exception has occured
// NOT for MyException, because that is already handled above
}
finally{
// this will always be called,
// if there has been an exception or not
// if there was an exception, it is called after the catch block
}
Finally blocks are important to release resources such as database connections or file handles no matter what. Without them, you would not have a reliable way to execute clean-up code in the presence of exceptions (or return, break, continue and so on out of the try block).
It allows you to attempt an operation, and in the event an Exception is thrown, you can handle it gracefully rather than it bubbling up and being exposed to the user in an ugly, and often unrecoverable, error:
try
{
int result = 10 / 0;
}
catch(ArithmeticException ae)
{
System.out.println("You can not divide by zero");
}
// operation continues here without crashing
try is often used alongside catch for code that could go wrong at runtime, an event know as throwing an exception. It is used to instruct the machine to try to run the code, and catch any exceptions that occur.
So, for example, if you were to request to open a file that didn't exist the language warns you that something has gone wrong (namely that it was passed some erroneous input), and allows you to account for it happening by enclosing it in a try..catch block.
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
}
An optional finally clause can be used after a try..catch block to ensure certain clean-up (like closing a file) always takes place:
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
} finally {
// Close the file object, so as to free system resourses.
file.close();
}
Exception handling
You're talking about a "try/catch" block. It's used to capture exceptions that may occur within the block of code inside the "try/catch". Exceptions will be handled in the "catch" statement.
It allows you to define an exception handler for a block of code. This code will be executed and if any "exception" (null pointer reference, I/O error, etc) occurs, the appropriate handler will be called, if one is defined.
For more information, see Exception Handling on wikipedia.
I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?
Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.
It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?
With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.
Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.