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
Related
we specify the exception in try and catch.If we know what exception is gonna be generated why go for exception handling rather than just debug that part of the code?
According to Oracle definition of Exception
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
CONCLUSION:
If you put a try {} catch block you know will always trow an Exception, your code is wrong.
For example, this code compiles? YES, but is wrong
String s = "throwMe!";
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
}
CORRECT EXCEPTION USE
System.out.println("Enter a number");
String s = Scanner..... // user enters something
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
// TELL USER THERE IS A PROBLEM
}
// TELL USER IS A GENIUS
This will have 2 execution flows, the correct one (user is a genius) but in the moment the user enters a value disrupting the flow (Integer.parseInt(s);) the Exception is thrown...
No, exceptions refer to run-time conditions that we cannot foresee
For example, the divide-by-zero error happens due to user inputting wrong data.
So you catch with try-catch
try {
}
catch(ArithmeticException){
}
You don't have to do exception handling or debugging, you can do both and good exception handling helps you debug your code later on.
If nothing else a catch block should print the Stack Trace which gives you information regarding where things went wrong with your code and it's much better than failing silently and then manually debug your whole code to search for the problem.
There are many other advantages to using exceptions for error handling as well.
Try / catch blocks are for errors that you cannot foresee. Things like null pointers and divide by 0 errors don't need a try catch blocks. Those things are typically errors on the part of programmers and should be debugged by the programmers. But things like IOException or SQLException, where you are interfacing with some other system that could fail or give invalid input that the programmer cannot control, those things need a try / catch block.
I have a static method used to get the title from a PDF using the metadata via itext, which is used as a small part of a major Task.
I noticed an inexplicable path that I narrowed down to this section of code. Specifically, in the line where I instantiate a PdfReader, the process doesn't throw an exception or continue through to the print statement. In fact, it clears out all of my for loops up to the top level of my program and acts as if nothing has happened and my task completed.
try {
System.out.println("Entered method");
PdfReader myReader = new PdfReader(file.getAbsolutePath());
System.out.println("Reader instantiated"); //if no issues, prints to console
Map<String, String> info = myReader.getInfo();
System.out.println(info.get("Title"));
return info.get("Title");
} catch (IOException e) {
System.out.println("PdfReader throws exception"); //if issues, prints to console
e.printStackTrace();
}
Unless I'm mistaken, when this set of code is executed in my method, either "Reader Instantiated" or "PdfReader throws exception" is printed out to the console.
Neither happens. Instead, the process skips every if/for/while loop it is currently in and ends the task.
I'm wondering if someone can explain to me what is happening and how I should go about fixing it?
In the odd event this is searched for, yes, catching Throwable stops the thread from bailing out. I had never seen something like this before. The cause behind the problem was that a PDF was password-protected, so getInfo() failed.
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.
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 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...
}