call to ioexception throwing function - java

I cannot call this function although it does throw amnd handle IOException
public static String[] readtxt(String f) throws IOException{
try{
FileReader fileReader=new FileReader(f);
BufferedReader bufferedReader=new BufferedReader(fileReader);
List<String> lines=new ArrayList<String>();
String line=null;
while((line=bufferedReader.readLine())!=null)lines.add(line);
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}catch(IOException e){return null;}
}
...
private String[] truth=MainActivity.readtxt(file);
// ^ wont compile: Unhandled exception type IOException

You either need to handle the Exception your method is throwing like this
try{
private String[] truth = MainActivity.readtxt(file);
}catch(IOException ioe){
// Handle Exception
}
Or you can remove the throws clause from your method definition like this
public static String[] readtxt(String f) {
Looking at your code, I really doubt if the method will actually throw any IOException since you already caught. Therefore you can remove that clause.
But if you really want to throw that, then you can either remove the try-catch in your method or do something like this in your catch block
catch(IOException ioe){
// Throw IOE again
throw new IOException(ioe);
}

You define your method as throwing IOExceptions;
public static String[] readtxt(String f) throws IOException
This means that any method that calls this method must deal with such exceptions (in a catch block), you are not dealing with them in the method calling this method and so this error is raised.
However, you have handled any IOExceptions that might be thrown. It is not nessissary (or correct) to claim that the method could throw an IOException because it never will. Simply remove throws IOException.
You have handled the exception by returning null, this may or may not be correct depending on your implementation. On an IOException a null will be returned and the program will continue as if nothing happened, you may alternatively want to give an error message but as I say this depends on your exact circumstances

You need to handle the exception like below
try{
private String[] truth=MainActivity.readtxt(file);
}catch(IOException exception){
exception.printStackTrace()
}

Related

My program is outputting a warning because of IOException?

How do you fix this warning: unreachable catch clause? I have seen people do catch IOException after FileNotFound and I don't know what is the problem.
public void run() {
int count = 0;
try {
Scanner scan = new Scanner(new FileInputStream(file));
while(scan.hasNext()) {
scan.next();
count++;
}
} catch(FileNotFoundException exception) {
System.out.println(file + " not found");
} catch(IOException exception) {
exception.printStackTrace();
}
You can get rid of the code
} catch(IOException exception) {
exception.printStackTrace();
}
reason being the only exception thrown within your try block is FileNotFoundException and its a subclass of IOException. Further to trace the exception this should suffice :
catch(FileNotFoundException exception) {
System.out.println("" + " not found");
exception.printStackTrace();
}
The only exception thrown from your code, which is in the IOException family of exceptions, is FileNotFoundException. Since you have a catch block for it (specifically) already, the IOException catch block becomes redundant.
In others' cases, they might be doing something else within the try-catch that also throws a different exception in the IOException family (or perhaps throws IOException itself), so catching IOException makes sense. For instance, consider this code:
FileInputStream fis = new FileInputStream(file);
fis.read();
If you wrap this in a try-catch block, you can catch both FileNotFoundException and IOException and there won't be warnings. The second line throws IOException directly.
As can be seen here, Scanner swallows any IOExceptions thrown by the underlying Stream during read. If you're concerned about handling problems with the reading of the file, you have two options:
a) Don't use Scanner but instead, some lower-level API like a Reader or an InputStream.
b) Once your while loop completes, do this (though it's a very uncommon thing to do):
if (scan.ioException() != null) {
throw scan.ioException();
}

In Java, how to force an Exception to "bubble up"?

I have a method that throws an Exception, which calls a method which throws an Exception, etc etc. So several methods that "throw Exception" are daisy-chained.
The first method that calls the submethod, puts that submethod in a try-catch block that catches any Exception that gets thrown inside that call. IN THEORY. In practice, no Exception is being caught by that try-catch block. Is there a way to remedy that?
Here is the code:
try {
CSVSingleton.tryToReadBothFiles(FILE1_PATH, FILE2_PATH);
} catch (Exception e) { // THIS BLOCK NEVER GETS ENTERED BY THE PATH O EXECUTION
System.out.println("There was an exception reading from at least one of the files. Exiting.");
System.exit(0);
}
here is the method from the CSVSingleton class:
public static void tryToReadBothFiles(String filePath1, String filePath2) throws Exception {
file1 = new CSVFileForDwellTime1(filePath1);
file2 = new CSVFileForDwellTime2(filePath2);
}
And here is code from the CSVFileForDwellTime1 class:
public CSVFileForDwellTime1(String filePath) throws Exception {
super(filePath);
}
and then here is the code that actually throws an original FileNotFoundException:
public GenericCSVFile(String filePath) throws Exception{
this.filePath = filePath;
try {
fileReader = new FileReader(filePath);
csvReader = new CSVReader(
fileReader);
header = getActualHeaderNames();
} catch (FileNotFoundException e) {
System.out.println("Could not read file with name: " + filePath);
// e.printStackTrace();
}
}
My guess is that the FileNotFoundException in the last method is caught by the catch block and so doesn't "bubble up". But is there a way to force it to bubble up?
Immediate answer:
Your thought is exactly right,
try {
fileReader = new FileReader(filePath);
csvReader = new CSVReader(
fileReader);
header = getActualHeaderNames();
} catch (FileNotFoundException e) {
System.out.println("Could not read file with name: " + filePath);
// e.printStackTrace();
}
This suppresses the exception
Either remove the try-catch block (desired unless you can actually do something with the exception)or re-throw it within the catch block.
Explanation
Generally with checked exceptions like this you have 2 options
Catch the exception and do something to remedy the exception
Throw the exception to the caller
What you have done here falls into the 1st category except that you have not done anything useful in the catch block (printing to console is rarely useful in this case because the exception message itself normally has enough information to see what has gone wrong)
The 2nd category is achieved either by not using a try-catch block and thus adding throws FileNotFoundException to the method signature. Alternatively explicitly throw the exception that you caught using:
catch(FileNotFoundException e)
{
//do something
throw e;
}
however in this case if do something isn't worthwhile you have unnecessarily caught something just to throw it on.
You can think of it like this:
Alice throws a ball to Charlie
Bob intercepts the ball
Bob then looks at the ball and then throws it to Charlie
Bonus Points
When you know the exception that could occur make sure to actually catch or throw that exception and not a parent of that exception.
Take the following method signatures for example:
public String method1() throws Exception
public String method2() throws FileNotFoundException
Here method2 clearly tells the caller what could happen and can help then figure out why the exception is being called (without having to read through the code or experience the error).
Secondly other exceptions can occur and you are potentially catching the wrong exception, take the following example:
try{
fileReader = new FileReader(filePath); //could potentially throw FileNotFoundException
fileReader = null; //woops
csvReader = new CSVReader(fileReader); //throws NullPointerException but the compiler will not know this
//....other stuff....//
}
catch(Exception e){
// the compiler told me that a FileNotFoundException can occur so i assume that is the reason the catch has executed
System.err.println("You have entered an invalid filename");
//doing anything here that would fix a FileNotFoundException is pointless because that is not the exception that occured
}
Use a throw in the catch clause.
} catch (FileNotFoundException e) {
System.out.println("Could not read file with name: " + filePath);
// Continue up, Mr. Exception!
throw e;
}
Alternatively, wrap the exception as appropriate (since an IOException is checked this handy here) - this is called a Chained Exception. Then, depending on what is thrown, the throws Exception can be removed from the method signature.
throw new RuntimeException("Could not read file: " + filePath, e);
If you don't want to catch it, then don't. Alternatively, you can just throw it again with a throw-statement. You can also throw a new Exception of any class you like. You should only catch an Exception at a level where you can react to it properly. As you found out, catching it at that low level is not helpful, so do not catch it there.
You can rethrow the exception once you catch it, for callees further up the stack to handle. You can change what exception it is too if a new type of exception makes more sense at a higher level.
catch (SomeSpecificException e)
{
some code here
throw new AMoreBroadException("I really need the callee to handle this too");
}
Technically you just need to add throw e right after System.out.println("Could not read file with name: " + filePath); and the exception will propagate up to the first method.
However, this would not be a clean way to handle the exception, because in this case all you'd be doing is printing an error message at the cost of changing the location of the original FileNotFoundException. Ideally, when you need to inspect an exception stacktrace, you expect a line of code throwing an exception to be the actual line that really caused the exception.
The throws Exception in the method declaration should be considered part of the contract of the method, i.e. it describes a possible behavior of the method. You should always ask yourself: Does it make sense for a FileNotFoundException to be specified as a possible exceptional behavior for the method/constructor I'm writing? In other words, do I want to make the caller of my method aware of this exception and leave it to the caller to deal with it? If the answer is yes (and in this case I would say it makes sense), then avoid wrapping the code in a try-catch block. If no, then your catch block should be responsible for dealing with the exception itself. In this specific example IMO there is not much you can do in the catch statement, so just remove the try-catch.
As mentioned by others, you should declare the most specific exception in the method signature (throws FileNotFoundException instead of throws Exception).

What is the correct way to silently close InputStream in finally block without losing the original exception?

I am wondering if the below code closes InputStream in finally block correctly
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
is.close();
} catch(IOException e) {
}
}
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Best way is to use Java 7 and use try with resources, or do same thing manualy and add exception from closing as suppressed exception.
Pre Java 7:
If you are throwing your custom exception, you can add in it supressed exception like it is done in Java 7 (in your exception create fields List suppressed and put there exceptions from close operation and when dealing with your exception, look there too.
If you cannot do that, I don't know anything better than just log it.
examples:
from Java tutorials
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
but better form is:
static String readFirstLineFromFile(String path) throws IOException {
try (FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr)) {
return br.readLine();
}
}
This way even if creation of FileReader is succesfull but creation of BufferedReader fails (eg not enough memory), FileReader will be closed.
You can close it with IOUtils from https://commons.apache.org/proper/commons-io/
public void readStream(InputStream ins) {
try {
//do some operation with stream
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(ins);
}
}
The Java 6 specs say
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So you are right, you will lose the original exception.
The solution probably is to write your finally block so defensively that it is a bigger surprise (worth propagating) if the finally block fails than if an exception comes out of the try catch block.
So, for example, if it is possible that the stream may be null when you try to close it, check it:
InputStream is = new FileInputStream("test");
try {
for(;;) {
int b = is.read();
...
}
} finally {
try {
if( is!=null ) {
is.close();
}
} catch(IOException e) {
}
}
In Java 7, Alpedar's solution is the way to go of course.
The exception from is.close() will be suppressed and the exception from is.read() will be the one that propagates up.
With the code you posted:
If is.close() throws an IOException, it gets discarded and the original exception propagates.
If is.close() throws something else (a RuntimeException or an Error), it propagates and the original exception is discarded.
With Java 7, the correct way to close an InputStream without loosing the original exception is to use a try-with-resources statement:
try (InputStream is = new FileInputStream("test")) {
for(;;) {
int b = is.read();
// ...
}
}
Prior to Java 7, what you do is just fine, except you may want to catch all exceptions instead of just IOExceptions.
Based on your code sample if an exception occurs at the int b = is.read(); point, then the exception will be raised higher up the call chain.
Note though that the finally block will still execute and if the Inputstream invalid another exception will be thrown, but this exception will be "swallowed", which may be acceptable depending on your use case.
Edit:
Based on the title of your question, I would add that what you have is fine in my opinion. You may want to additionally add a catch block to explicitly handle (or perhaps wrap) any exception within the first try block, but it is also acceptable to let any IO exceptions raise up - this really depends on your API. It may or may not be acceptable to let IO exceptions raise up. If it is, then what you have it fine - if it isn't then you may want to handle/wrap the IO exception with something more suitable to your program.
How about the next solution:
InputStream is = new FileInputStream("test");
Exception foundException=null;
try {
for(;;) {
int b = is.read();
...
}
} catch (Exception e){
foundException=e;
}
finally {
if(is!=null)
try {
is.close();
} catch(IOException e) {
}
}
//handle foundException here if needed
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Yes. You have a catch block for the exception in close() which does not re-throw the exception. Ergo it is not propagated or rethrown.
This is the sample to help to understand your problem,
if you declare the scanner in the try-catch block it will give compiler warning the resource is not closed.
so either make it locally or just in try()
import java.util.InputMismatchException;
import java.util.Scanner;
class ScanInt {
public static void main(String[] args) {
System.out.println("Type an integer in the console: ");
try (Scanner consoleScanner = new Scanner(System.in);) {
System.out.println("You typed the integer value: "
+ consoleScanner.nextInt());
} catch (InputMismatchException | ArrayIndexOutOfBoundsException exception) {
System.out.println("Catch Bowled");
exception.printStackTrace();
}
System.out.println("----------------");
}
}

Why am I getting "must be caught or declared to be thrown" on my program?

I have been working on this program for quite sometime and my brain is fried. I could use some help from someone looking in.
I'm trying to make a program that reads a text file line by line and each line is made into an ArrayList so I can access each token. What am I doing wrong?
import java.util.*;
import java.util.ArrayList;
import java.io.*;
import java.rmi.server.UID;
import java.util.concurrent.atomic.AtomicInteger;
public class PCB {
public void read (String [] args) {
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader("processes1.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
write(l);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
}
}
public void write(String table) {
char status;
String name;
int priority;
ArrayList<String> tokens = new ArrayList<String>();
Scanner tokenize = new Scanner(table);
while (tokenize.hasNext()) {
tokens.add(tokenize.next());
}
status = 'n';
name = tokens.get(0);
String priString = tokens.get(1);
priority = Integer.parseInt(priString);
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet();
int pid = count.get();
System.out.println("PID: " + pid);
}
}
I am about to poke out my eyeballs. I got three errors:
U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:24: unreported exception java.io.IOException; must be caught or declared to be thrown
inputStream.close();}
^
U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:15: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
inputStream = new BufferedReader(new FileReader("processes1.txt"));
^
U:\Senior Year\CS451- Operating Systems\Project1 PCB\PCB.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
while ((l = inputStream.readLine()) != null) {
^
What am I doing wrong?
When you work with I/O in Java most of the time you have to handle IOException which can occur any time when you read/write or even close the stream.
You have to put your sensitive block in a try//catch block and handle the exception here.
For example:
try{
// All your I/O operations
}
catch(IOException ioe){
//Handle exception here, most of the time you will just log it.
}
Resources:
oracle.com - Lesson: Exceptions
Java checks exception specifications at compile time. You must either catch the exception or declare it thrown in your method signature. Here's how you would declare that it may be thrown from your method:
public void read (String [] args) throws java.io.IOException {
Catch the exception if your method needs to do something in response. Declare it as thrown if your caller needs to know about the failure.
These are not mutually exclusive. Sometimes it is useful to catch the exception, do something and re-throw the exception or a new exception that wraps the original (the "cause").
RuntimeException and its subclasses do not need to be declared.
Good IDEs will either create the catch block for you or add the exception to the method declaration.
Be advised that if you add the exceptions to the method declaration as per Colin's solution, any method that invokes your method will also have to have a suitable catch block or declare the exception in the method declaration.
You could rather do
try{
// All your I/O operations
}
catch(Exception e){
//Handle exception here, most of the time you will just log it.
}
in general its not a bad idea to catch the class itself some time and decides you logic into catch or do a instanceof if you need very specific log.
whenever "unreported exception IOException; must be caught or declared to be thrown"
this error has come then required to put the code in try catch block.
Example
try{
// All your I/O operations
}
catch(IOException ioe){
//Handle exception here, most of the time you will just log it.
}
I have had the same problem. I got it solved by adding the spring library "org.springframework.core"

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