Java try and catch error - java

I am trying to try and catch an error in my method to write the contents of change drawer to a html document. The error, java.io.FileNotFoundException, appears when the file does not exist. The code below should do this but it comes up with the error "PartB is an incompatible type". I think there is an error in my try and catch code, this the first one I've written and I am at a loss as to why it won't work. Any help would be great. Thankyou.
...
public static void writeHtmlFile()
{
try {
BufferedReader in = new BufferedReader((new FileReader("changedrawer.html")));
String sLine;
StringBuilder sb = new StringBuilder();
while ((sLine = in.readLine()) !=null)
sb.append(sLine+"\n");
//Close file
in.close();
//Output on console
System.out.println(sb.toString());
}
catch (PartB FileNotFoundException) //Why is PartB an incompatible type? (PartB is the name
of the class)
{ System.out.println ("error");
}
...

The syntax for a simple "catch" clause is roughly as follows:
} catch (<exception-type> <identifier>) {
<optional-statements>
}
The <exception-type> is the name if the exception you are trying to catch, and <identifier> is the name of a local variable that you are declaring to hold the exception instance that you just caught.
In your cause, it should look like this:
catch (FileNotFoundExceptio ex) {
System.out.println ("error");
}
... though I'd recommend a more informative error message!
(Note that you have to declare a local identifier, even if you are not going to use it. But it is only a couple of characters, especialy if you use the conventional names e or ex.)

You need to write it as FileNotFoundException PartB, not PartB FileNotFoundException because FileNotFoundException is the type.

You declare an exception like you declare any object or variable:
Exception_Type identifier

Related

I need to use a try-catch, but it says it is an unreachable catch block. How do I make it reachable?

I'm new to coding, and very new to java, so please bear with me, I'm sorry.
My professor says we need to use the following code as part of our assignment. I've looked through all my notes for the class, and I cannot find anything on try-catch and I'm not sure what I'm supposed to put in the insert code part or what the error message means
I'm very sorry, I'm just very confused. I keep getting
"Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
and I don't know how to fix it
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner( file );
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Edit: I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body"
What am I supposed to put in the try statement? I am so lost
I didn't get that error again after fixing it until I tried hard-coding a text file to test things out.
try
{
File file = new File( args [ 0 ] );
Scanner scanner = new Scanner("cat.txt");
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
I am once again getting "Unreachable catch block for FileNotFoundException.
new Scanner(String) is not the same as new Scanner(File). If you look at the documentation, the first (using a String) reads from the string, not from a file. Since no file is involved, there's no FileNotFoundException.
If you want to hardcode the filename for testing purposes, do that in the new File(...) line, not the new Scanner(...) line:
try
{
File file = new File("cat.txt"); // <==== Here
Scanner scanner = new Scanner(file);
//insert code
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
That will compile, because new Scanner(File) throws FileNotFoundException.
Welcome to SO! Exceptions are a great way to catch errors and decide how to handle them. Some segments of code require the program to take a leap and attempt to perform a task that may not be possible at that moment.
The errors specified in the question are a result of the Scanner not finding the file at the specified file path. The ArrayIndexOutOfBounds is indicating exactly what the exception states. The index being accessed is outside the bounds(size) of the array.
Java docs is a great resource and this should help clarify the purpose of catch statements.
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

Catching Same IOException Inside Catch IOException Block

My Android code is behaving funny. The input stream should and does throw an IOException, which correctly causes control to go to // read an error stream. The error stream is read correctly and the debugger steps to return error_message with the error_message variable containing expected characters read from error stream. It then correctly steps to the // no op in the finally block, which I added just for kicks.
And then, it steps to return "all hope lost";!! Which then, instead of returning to the caller, steps into some Android system code that throws a SecurityException with a message about lack of content permissions.
Removing the finally block has no impact -- the bug still happens. The streams being read are from an HTTP URL Connection. No problems if server returns 200 but if server returns 400 it goes through the weird path described above and tries to throw the weird SecurityException.
try {
// read an input stream into message
return message;
} catch (IOException outer) {
try {
// read an error stream into error_message
return error_message;
} catch (IOException inner) {
return "all hope lost";
}
} finally {
// no op, just to step debugger
}
Update: Posting exact code and debug trace.
try {
/*x*/ BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getInputStream())));
StringBuilder string_builder = new StringBuilder();
String line;
for (line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
return string_builder.toString();
} catch (IOException io_exception) {
this.io_exception = io_exception;
BufferedReader buffered_reader =
new BufferedReader(
new InputStreamReader(
new BufferedInputStream(http_url_connection.getErrorStream())));
StringBuilder string_builder = new StringBuilder();
try {
for (String line = buffered_reader.readLine();
line != null;
line = buffered_reader.readLine()) {
string_builder.append(line);
}
/*y*/ String error_message = "server error: " + string_builder.toString();
return error_message;
} catch (IOException exception) {
String level_2_error_message = "level 2 error: " + exception.getMessage();
return level_2_error_message;
} finally {
return "foo";
}
}
Line /*x*/ causes the jump to the first catch as expected. All lines up to /*y*/ are then executed as expected. Then the weird thing is that line /*y*/ does not complete and control immediately goes to either the next catch block if there is no finally or to the finally. If there is a finally then it does not to got the last catch block.
The contents of the string buffer on /*y*/ line look perfectly fine -- a 20 character string from the server.
You say that an exception is being thrown by line /* y */
By my reading of that line of code, the following are plausible explanations:
The exception is a NullPointerException because string_builder is null. But it can't be.
The exception is an OutOfMemoryError because you don't have enough free space for the toString() call to create the new String object.
It is possible that StringBuilder is not java.lang.StringBuilder but some class you wrote yourself. In that case, any exception is possible.
However, I can't see how you would end up in the second IOException handler.
Apart from that, the only other likely explanation is that that source code does not match the code that you are actually executing; e.g. you forgot to recompile something, or you forgot to redeploy after your last compilation.
For what it is worth, your return in your finally is almost certainly a mistake.
It means that you will return "foo" instead of either of the error messages.
If (for example) string_builder.toString() did throw an NPE or OOME, then the return would squash it.
A finally with a return can have non-intuitive behaviour. It is certainly NOT something you should do "for debugging"!!!

Try catch exception (letter in int)

I'm trying to use a try catch structure to show an error when I try to input a letter into a string. Which exception should I be using for this? the console shows me InputMismatchException but this does not work.
input that works:
beginnen = 1
input that doesn't work:
beginnen = a
it obviously doesn't work cause i'm putting a string into an int, I just want to have a message show up when this occurs
int beginnen;
String error = "Something went wrong";
try {
beginnen = Input.readInt();
}
catch (InputMismatchException IME) {
System.out.println(error);
}
error that shows up:
Exception in thread "main" java.util.InputMismatchException
If the documentation is foggy, use experiment:
try {
beginnen = Input.readInt();
} catch (Throwable x) {
System.err.println("Catched "+x.getClass().getName());
}
This will print the exact class name for you and you can later change your code to catch the exception of this class. This will also show for you, maybe just nothing is actually thrown.
Your Try/Catch expression looks fine to me, however you've mistakenly referenced error, which is not defined anywhere.
Try changing it to System.out.println(IME.getMessage());

Help with try/catch and accessing elements within the try

try {
inFile = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
I have this code. However, after the try/catch statement I have the following:
while(inFile.hasNext()) {
}
The compiler is telling me that I have not initialized inFile. Do I need to put all of my code within the try/catch? What am I doing wrong?
Initialize inFile:
Scanner inFile = null;
Edit:
As others have mentioned, you should be careful that you could potentially get a NullPointerException in your while loop. You should consider moving your while loop into the try block as well:
Scanner inFile = null;
...
try {
inFile = new Scanner(file);
while(inFile.hasNext()) {
}
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
The compiler is complaining because if new Scanner() throws FileNotFoundException, inFile won't be initialized (BTW very unfortunate variable name). Your loop should be inside try block, which will also increase readability.
try {
Scanner inFile = new Scanner(file);
while(inFile.hasNext()) {
//...
}
inFile.close();
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
If you are getting a compiler error, you probably need to initialize inFile to null.
Note that later in your code you shouldn't assume that inFile is not null, you should always check it:
e.g.
if (inFile != null) {
while (inFile.hasNext()) {
...
}
}
Yes, you do. If an exception is raised the runtime will print "FileNotFoundException" and will keep running, although inFile will not have been initialized.
You should make the program return when stumbling upon this exception, or else do your operations on infile only when you are sure that it has been initialized correctly.
The try block is not in the same scope as your while loop. Put the while loop inside the try block.
The reason for the warning is that you should set the Scanner to null initially. However you should also move the while loop inside the try block, because if the exception is thrown you don't want that while loop to execute (because inFile will be null).
No your code is fine, however local variables must be intialized so you have to set Scanner inFile = null;
And it is correct what you already have done, because if you move the local variable inside the try/catch statement you will not have access to it because of the scope.
Scanner inFile = null;
try {
inFile = new Scanner(file);
//more code
} catch (Exception e) {
//exception code
}
while (inFile.nextLine()) {
//loop code
}
If you had an instance variable it would have been automatically set to null, but in this case you have a local variable and then objects need to be initialized before you use it.
Yes, as others have said, initialize inFile to null
However, you will also need to check that inFile actually points a valid file and is not NULL when you get to your loop
e.g.
while(inFile!=null && inFile.hasNext()) {
}
Otherwise, you perhaps want to place the whole try-catch in a different loop to make the user select another file? Or just exit the program if the file is invalid? The missing element to the question is how you wish to handle invalid files. Does the program exit or re-prompt the user?

Java exception handling method

I'm having a little bit of trouble implementing the following method while handling the 3 exceptions I'm supposed to take care of. Should I include the try/catch blocks like I'm doing or is that to be left for the application instead of the class design?
The method says I'm supposed to implement this:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException
This method loads the info from the archive specified in a catalog of products and returns the catalog.
It starts by opening the file for reading. Then it proceeds to read and process each line of the file.
The method String.startsWith is used to determine the type of line:
If the type of line is "Product", the method readProduct is called.
If the type of line is "Coffee", the method readCoffee is called.
If the type of line is "Brewer", the method readCoffeeBrewer is called.
After the line is processed, loadCatalog adds the product (product, coffee or brewer) to the catalog of products.
When all the lines of the file have been processed, loadCatalog returns the Catalog of products to the method that makes the call.
This method can throw the following exceptions:
FileNotFoundException — if the files specified does not exist.
IOException — If there is an error reading the info of the specified file.
DataFormatException — if a line has errors(the exception must include the line that has the wrong data)
Here is what I have so far:
public Catalog loadCatalog(String filename)
throws FileNotFoundException, IOException, DataFormatException{
String line = "";
try {
BufferedReader stdIn = new BufferedReader(new FileReader("catalog.dat"));
try {
BufferedReader input = new BufferedReader(
new FileReader(stdIn.readLine()));
while(! stdIn.ready()){
line = input.readLine();
if(line.startsWith("Product")){
try {
readProduct(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Coffee")){
try {
readCoffee(line);
} catch(DataFormatException d){
d.getMessage();
}
} else if(line.startsWith("Brewer")){
try {
readCoffeeBrewer(line);
} catch(DataFormatException d){
d.getMessage();
}
}
}
} catch (IOException io){
io.getMessage();
}
}catch (FileNotFoundException f) {
System.out.println(f.getMessage());
}
return null;
}
It depends on whether you want the class or another portion of the application that is using it to handle the exception and do whatever is required.
Since the code that will use the loadCatalog() probably won't know what to do with a file I/O or format exception, personally, I'd go with creating an exception like CatalogLoadException and throw it from within the loadCatalog() method, and put the cause exception (FileNotFoundException, IOException, DataFormatException) inside it while including an informative message depending on which exception was triggered.
try {
...
//do this for exceptions you are interested in.
} catch(Exception e) {
//maybe do some clean-up here.
throw new CatalogLoadException(e); // e is the cause.
}
This way your loadCatalog() method will only throw one single and meaningful exception.
Now the code that will use loadCatalog() will only have to deal with one exception: CatalogLoadException.
loadCatalog(String filename) throws CatalogLoadException
This also allows your method to hide its implementation details so you do not have to change its "exception throwing" signature when the underlying low level structure changes. Note that if you change this signature, every piece of code would need to change accordingly to deal with the new types of exceptions you have introduced.
See also this question on Exception Translation.
Update on the throwing signature requirement:
If you have to keep that signature then you don't really have a choice but to throw them to the application and not catch them inside the loadCatalog() method, otherwise the throws signature would be sort of useless, since we aren't going to throw the exact same exception that we have just dealt with.
The general idea is that you percolate exceptions up to the appropriate place to handle them. I am going to guess that your instructor expects them to be handled in main. In this case I can guess that because of the throws clause you were given. A simple rule of thumb is that if the method declares the exception in the throws clause you do not catch it in that method. So the method you are writing should have no catch statements.
To do that you would change your code something like:
public Catalog loadCatalog(String filename)
throws FileNotFoundException,
IOException,
DataFormatException
{
String line = "";
BufferedReader stdIn = new BufferedReader(new FileReader("catalog.dat"));
BufferedReader input = new BufferedReader(new FileReader(stdIn.readLine()));
while(!stdIn.ready())
{
line = input.readLine();
if(line.startsWith("Product"))
{
readProduct(line);
}
else if(line.startsWith("Coffee"))
{
readCoffee(line);
}
else if(line.startsWith("Brewer"))
{
readCoffeeBrewer(line);
}
}
return null;
}
and then in the method (presumably main) that calls loadCatalog you would have:
try
{
loadCatalog(...);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(DataFormatException ex)
{
ex.printStackTrace();
}
replacing the printStackTrace with something appropriate.
That way the method, loadCatalog, doesn't deal with displaying the error messages, so you can call the method in GUI or console code and the code that calls it can choose how to display the error to the user (or deal with it in some way).
Here is an excellent article of Heinz Kabutz, dealing with exception handling.
http://www.javaspecialists.eu/archive/Issue162.html

Categories

Resources