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...
}
Related
I am getting fortify issue as :
Poor Error Handling: Throw Inside Finally
I am not throwing exception inside finally block, but still it is showing this error.
Please find the code below.`
catch( IOException | JSONException | URISyntaxException e)
{
if(instream == null) {
throw new IOException("InputStream not valid");
}
return e.getMessage();
}finally {
if(instream != null ) {
instream.close();
}
if(urlConnection != null ) {
urlConnection.disconnect();
}
}
No, you are: inStream.close() can throw.
Generally, 'curing' the warning is actually going to make your code worse. This is the problem:
IF the try block throws an uncaught exception
In this case, the finally block is executed. Let's say that the finally block runs in.close();. Especially if the entire reason we got here is that in got disconnected and started throwing IOEx, this is likely to also throw an IOEx. Any exceptions thrown out of a finally block 'overwrite' the exception that caused us to be here, and the stack trace from that close call is far less useful.
So this is bad.
We can fix it by wrapping the in.close() in your finally block in a try { .. } catch (Exception ignore) {}. But then, the other scenario is really bad:
IF we get here 'normally'
It's possible for an input stream to work perfectly, and then when you close it, it throws. For a good long while common wisdom was 'eh, whatever, who cares, I got my data', but that's not a sensible idea: If an input's close ends up throwing, that probably means you didn't actually get all data yet, otherwise, why did it do that? So, now, silently swallowing any exceptions is a bad idea, and we want to throw it.
Without bending over backwards, using a boolean to track how we got to the finally block and depending on it, swallowing that exception or not, it is not possible to do it right.
Because this is so tricky, try-with-resources actually does it right and generates the requisite boilerplate.
Thus, the REAL solution: If you are closing resources in a finally block, don't. Use the try (ResourceType r = new ResourceType()) { ... } syntax instead.
If you truly can't do that, and you also can't make it work by creating a wrapper that is AutoClosable and will for example do nothing if the resource is null, then you're basically forced to tell your linter to stop complaining about this.
I'm new to the world of programming. I am on my 6th class and we were tasked to create a new file using an instance of File. I'm getting an io exception when compiling. I searched online but I can't seem to find an explanation I can understand about the issue.
Please bear with me but my code is:
import java.io.File;
public class TestFile{
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = myArchive.createNewFile();
System.out.println(x);
}
}
As I understand createNewFile() will provide a true value if the file is created, but I keep getting the following message.
TestFile.java:5: error: unreported exception IOException; must be
caught or decl ared to be thrown
boolean x = myArchive.createNewFile();
^ 1 error
From what I gathered online, there's an exception that needs to be caught. The instructor didn't advise of how to handle an exception on the code or anything to do with the commands try or catch.
Thank you very much for you assistance. If I'm not complying with any of the forums' guidelines, please let me know, this is my first post and again I'm fairly new to programing.
In java you will get many Exceptions and you have to handle It using try..catch block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Additionally you have to define boolean x outside the try block and should be initialized to some value (either true or false) .
Try this code:-
import java.io.File;
public class Main {
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = true;
try {
x = myArchive.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(x);
}
}
Output:-
true
Just an intro to try-catch and what's it for:
Some operations may generate an error, which may even not be a mistake of the programmer, but may happen due to unforeseen circumstances.
For example, you want create a file, but at this moment, the file destination may become absent (e.g., a usb stick is taken out), or the disc may be full, or it may be an impossible filename (provided by another user through the keyboard, containing "forbidden" characters), or permission may not be given (e.g. in Android, when your phone asks for permissions to write files, you may grant it, or you may refuse to grant it for security's sake).
For such cases, Java provides you with an opportunity to try the error-prone code, and then catch the error. If an error happens, you don't want your app to crash. You want it to continue continue working, so you may warn the user on the screen that the file operation failed, and provide alternative actions.
So, basically, you do the following
try{
// place a risky part of code here
// like, creating a file
} catch (Exception error)
{
// This part will be executed only if there is an error
// in this part, you can change the wrong file name
// or tell the user that the disc is not available
// just do something about the error.
// If an error does not occur, then this part will not be executed.
}
try {
boolean x = myArchive.createNewFile();
System.out.println(x);
} catch (IOException e) {
e.printStackTrace();
}
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block
Ok I know catching throwable is not a good idea:
try {
// Some code
} catch(Throwable e) { // Not cool!
// handle the exception
}
But recently I was reading through an open sourced code and I saw this interesting (at least to me) piece of code:
try {
// Some Code
} catch (Throwable ex){
response = handleException(ex, resource);
}
private handleException(Throwable t, String resource) {
if (t instanceof SQLEXception) {
// Some code
} else if (t instanceof IllegalArgumentException) {
//some code
} //so on and so forth
}
This doesn't seem to be that bad? What is wrong with this approach?
There are various reasons why you should not catch a Throwable. First of all is, that Throwable includes Errors - and there's normally not much an application can do if one of these appears. Also Throwable reduces your chances of finding out, WHAT has happened. All you get is "something bad has happened" - which might be a catastrophe or just a nuisance.
The other aproach is better but of course I still would not catch Throwable, but try to catch more specific Exceptions, if possible at all. Otherwise you are catching everything and then try to sort out which kind of bad thing happened. Your example could be written as...
try {
...
} catch (SQLEXception ex){
response = ... ;
} catch (IllegalArgumentException ex){
response = ...;
}
...which would reduce the amount of if ( ... instanceof ... ) blocks (which are only needed because the author first decided to catch everything in one big bucket). It something actually throws Throwable, then you don't have much choice, of course.
You are right when you say that catching Throwable is not a good idea. However, the code that you present in your question is not catching Throwable in an evil way but let's talk about that later. For now, the code that you present in your question has several advantages :
1. Readability
If you look at the code carefully, you will notice that even though the catch block is catching a Throwable, the handleException method is checking the type of exception thrown and possibly taking different actions based on the exception type.
The code presented in your question is synonymous to saying:
try {
doSomething();
} catch (SQLEXception ex){
response = handleException(resource);
} catch(IllegalArgumentException ex) {
response = handleException(resource);
} catch(Throwable ex) {
response = handleException(resource);
}
Even if you have to catch 10+ exceptions only, this code can easily take up a lot of lines of code and the multi-catch construct is not going to make the code any cleaner. The code that you present in your question is simply delegating the catch to another method to make the actual method that does the work more readable.
2. Reusability
The code for the handleRequest method could easily be modified and placed in a utility class and accessed throughout your application to handle both Exceptions and Errors. You could even extract the method into two private methods; One that handles Exception and one that handles Error and have the handleException method that takes a Throwable further delegate the calls to these methods.
3. Maintainibility
If you decide that you want to change the way you log an SQLExceptions in your application, you have to make this change in a single place rather than visiting every method in every class that throws an SQLException.
So is catching Throwable a bad idea?
The code that you present in your question is not really the same as catching Throwable alone. The following piece of code is a big no-no:
try {
doSomething();
} catch(Throwable e) {
//log, rethrow or take some action
}
You should catch Throwable or Exception as far away in the catch chain as possible.
Last but not the least, remember that the code you present in your question is framework's code and there are certain errors that the framework can still recover from. See When to catch java.lang.Error for a better explanation.
Catching Throwables out of laziness is a bad idea.
This was particularly tempting before try-multi-catch was introduced.
try {
...
} catch (SomeException e) {
//do something
} catch (OtherException e) {
//do the same thing
} ...
Repeating catch blocks is tedious and verbose, so some people decided to just catch Exception or Throwable and be done with it. This is what should be avoided because:
It makes it difficult to follow what you're trying to do.
You may end up catching a lot of stuff you can't deal with.
You deserve bonus punishment if you completely swallow the Throwable in the catch block. (And we've all seen code that does that...:))
But catching Throwables when it is absolutely necessary is fine.
When is it necessary? Very rarely. In framework-style code there are various scenarios (dynamically loading an external class is the most obvious one), in a standalone application a typical example is to attempt to display/log some kind of error message before exiting. (Bearing in mind that the attempt may fail, so you don't want to put anything critical there.)
As a rule of thumb, if there's nothing you can do about an exception/error, you shouldn't catch it at all.
You posted a link to Jongo, which demonstrates one possible use for this technique: re-using error handling code.
Let's say you've got a large block of error handling code that naturally repeats itself in various places in your code - for example Jongo produces standard responses for some standard classes of errors. It may be a good idea to extract that error handling code into a method, so you can re-use it from all the places it's needed.
However, that's not to say that there's nothing wrong with Jongo's code.
Catching Throwable (rather than using multicatch) is still suspicious, as you're likely to catch Errors that you're not really in a position to handle (are you sure you meant to catch ThreadDeath?). In this situation, if you absolutely have to catch Throwable, it'd be better to "catch and release" (i.e, rethrow anything that you didn't mean to catch). Jongo doesn't do this.
There are exactly two valid uses for using a huge net:
If you will handle everything uniformly, like a top-level catch for logging/reporting, possibly followed by an immediate exit.
To reduce duplication, by exporting all the handling into its own method.
Catch the most derived common ancestor there is to avoid extra-work and increase clarity.
DRY is an important design principle.
In both cases, unless you expected that exception and handled it completely, rethrow.
First of all, catching Throwable makes your application rather intransparent. You should be as explicit as possible on catching exceptions to enable good traceability in exceptional cases.
Let's have a look at the method handleException(...) and see some of the problems that occur by this approach:
you catch Throwable but you only handle Exceptions, what happens if an e.g. OutOfMemoryError of type Error is thrown? - I see bad things to happen...
Regarding good object oriented programming using instanceof breaks the Open-Closed-Principle and makes code changes (e.g. adding new exceptions) really messy.
From my point of view, catch-blocks are exactly made for the functionality that are tried to cover in handleExceptions(...), so use them.
Java 7 solves a bit of the tedium that is multi-catching of similar exceptions with similar handling. You definitely should not be doing what the person has done here. Just catch the appropriate exceptions as needed, it may look ugly but then that's what throws is for, pass it to the method that should catch it and you shouldn't be wasting too much code space.
Check out this link for more information.
Just to provide balance - there is one place where I will always catch (Throwable):
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
At least something shows somewhere that something went wrong.
You can always catch different type of exceptions and perform some operations based on the type of the exception you got.
Here is an example
try{
//do something that could throw an exception
}catch (ConnectException e) {
//do something related to connection
} catch (InvalidAttributeValueException e) {
// do anything related to invalid attribute exception
} catch (NullPointerException e) {
// do something if a null if obtained
}
catch (Exception e) {
// any other exception that is not handled can be catch here, handle it here
}
finally{
//perform the final operatin like closing the connections etc.
}
In my program I have to constantly access the hard drive thousands of times to view images (no way around it), occasionally my program gets tripped up on a "file not found IO Exception" most likely because of the many modifications I'm making to the images and re saving quickly. How do I continue my program even if this error occurs, because currently it causes my program to stop?
Code:
filepattern=imageLocation+temp+"image.jpg";
File outputfile = new File(filepattern);
BufferedImage img = null;
try {
img = ImageIO.read(outputfile);
} catch (IOException e) {
}
Note: I have fixed the problem by making sure the file exists first. Thanks for all your help!
Catch the exception and handle it as needed.
try {
// your code
} catch (<Expected exception> e) {
// handle the exception
}
Surround the statement with a try catch.
This will stop the code from crashing and in the catch block you can write code to deal with the failure.
There are 3 key words
try {}
executes the block that can cause problems
catch (Exception ex) {}
executes code to handle specific exceptions. Instead of Exception you can handle specific exception types
finally {}
executes cleanup code. Even if exception occurs and breaks the execution flow in try block, this code will always execute.
You might try something like the fragment below. Of course, you will want to encapsulate the actual reading in a try / catch / finally block to make sure you close the file
try {
filesTried++;
[you code]
} catch (IOException e) {
fileErrors++;
I can't seem to phrase this correctly for the search engine to pick up any meaningful results.
try{
BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
}
catch(Exception e){
println( e.getMessage() );
}
So FileReader only throws the FileNotFoundException, which as I understand it is an IOException, which is an Exception. Can someone explain why I would catch FileNotFoundException or IOException instead of just specifying the generic "Exception" and not having to import an exception (i.e. import java.io.FileNotFoundException;)? Is it strictly for readability?
I've caught the exception using all three names and I can't find a difference.
EDIT:--------------------
private BufferedReader askUserForFile(String prompt){
BufferedReader rd = null;
while(rd == null){
try{
String filename = readLine(prompt);
rd = new BufferedReader( new FileReader(filename) );
}
catch(Exception e){
println(e.getMessage());
}
}
return rd;
}
Exception is the mother of all exceptions, including all RuntimeException subclasses. When you specify to catch it, you'll get much more fish in the net than you wanted, like NullPointerExceptions, IllegalArgumentExceptions and so on.
While catching the generic Exception is the right thing to do at some point in your code, catching it at any lower layer is almost certainly wrong and can hurt the behavior of your application.
The more important skill to learn in Java is not how to catch exceptions, but how to not catch them, instead letting them propagate up the call stack, towards the exception barrier, the one common spot in the code where all errors are caught and uniformly handled (typically by logging, rolling back the transaction, and similar).
The difference is there could be other problems inside the code of your try block that could throw other types of Exceptions including subclasses of RuntimeException (which don't have to be declared).
If you just catch Exception, then you will catch all of those other errors too which may hide a different problem. Also your code inside the catch block can't assume the Exception happened due to an IOException since any kind of exception will be caught.
As a followup to dkatzel's answer, let's assume you start to read from the file in the same try block and the file tells you which value in a array of options to use:
String toPrint = {"Hi", "World", "I'm", "A", "String", "Array"};
try{
BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
String line = reader.readLine();
System.out.println(toPrint[Integer.parseInt(line)]);
}
catch(Exception e){
println( e.getMessage() );
}
Now you have absolutely no idea what really went wrong except through the stack trace. You can't handle any fixable problems. You can't tell in code whether the file doesn't exist (FileNotFoundException), you don't have access to the file, (IOException), if the first line wasn't an Integer (NumberFormatException), or the number was bigger than the array length (ArrayIndexOutOfBoundsException). If you wanted to print a default value if you couldn't read the number, you could instead catch a NumberFormatException and print the value instead of having to quit the entire program.
I'll admit this is a pretty contrived example, but it should give you an explanation of why catching Exception is bad. Marko also has a very good answer, stating that it usually is better to let the exception propagate up (especially with RuntimeExceptions) than to create a bunch of messy code trying to deal with every single problem that can happen.
What if you want to do a different action with different exceptions? You can make a catch block for IOException and for example, make it show a message box. Then make another catch block for a FileNotFoundException and make it create a new file and try to open it again, or even rethrow the exception. Hope I explained myself correctly. Cheers!
The reason is whenever you program, you have to think about all the possibilities and it is useful to do something for a specific error. Exception is a catch all method of catching errors and will handle all exceptions the same. IOException will catch any IO Exceptions so it will treat file not found and and other IO Exception (like EOFException) the same. FileNotFoundException will only catch file not found exceptions so you can handle it instead of just logging it.
Some errors will happen and being able to handle each individual case keeps your program running. In this case, file not found can make you select another file so the program doesn't crash and it handles the situation.
FileNotFoundException is an IOException which is an Exception
You are right. But if you catch Exception objects you will catch any exception triggered by your code, not only the FileNotFound exception.
Let's say that your code can throw more than one kind of exception:
try {
/*
* Code, code and more code
*/
} catch(ExceptionType1 e) {
System.err.println("Something went wrong! It is a type 1 exception");
} catch(ExceptionType2 e) {
System.err.println("Something went wrong! It is a type 2 exception");
} catch(Exception e) {
System.err.println("Something went wrong! It is not any of the known exception types");
}
Compare the above possibility with this:
try {
/*
* Code, code and more code
*/
} catch(Exception e) {
System.err.println("Something went wrong! Can be exception type 1, 2 or something else");
}
As you can see, differentiating the exception types can help you understand what went wrong in your code.