aelgoa
aelgoa

Reputation: 1201

call to ioexception throwing function

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

Upvotes: 0

Views: 2296

Answers (3)

Richard Tingle
Richard Tingle

Reputation: 17226

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

Upvotes: 0

Rahul
Rahul

Reputation: 45070

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);
}

Upvotes: 2

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You need to handle the exception like below

 try{ 
      private String[] truth=MainActivity.readtxt(file); 
 }catch(IOException exception){
      exception.printStackTrace()
 }

Upvotes: 0

Related Questions