tags:

views:

325

answers:

4

I'm having trouble with the following code. I'm trying to write to a .ppm file, and I get

"Red.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown" FileOutputStream fout = new FileOutputStream(fileName); ^ Any ideas?

import java.io.*;

public class Red {

public static void main(String args[]) {

String fileName = "RedDot.ppm"; 
FileOutputStream fout = new FileOutputStream(fileName); 
DataOutputStream out = new DataOutputStream(fout);

System.out.print("P6 1 1 255 ");
    System.out.write(255);
    System.out.write(0);
    System.out.write(0);
    System.out.flush();
}

}

+3  A: 

Th FileNotFoundException is a checked exception. You need to enclose the code that trys to write to the file in a try/catch block, or throw the exception.

Sam Cogan
"or throw the exception". Declare the exception as thrown, surely ?
Brian Agnew
A: 

Are you writing your code in Notepad? Try using Eclipse. It would underline the code that has the problem with uncaught exception and then you could just place the cursor in the underlined section (the line that gives errors), press Ctrl+1 for a list of solutions, and pick one on the list. I suppose surrounding the block with a try{}catch{} would hush the exception, unless you -want- to do something about it.

Peter Perháč
I'm using emacs for now.
FarmBoy
if all you want for your homework is to shut up the error message, then place all of your code in a tr { } block and at the end type catch (Exception e) {}. This will hush up anything. Although don't EVER do this in the future and read a chapter on Java Exception Handling.
Peter Perháč
+3  A: 

The simplest solution is to rewrite your main declaration thus:

public static void main(String args[]) throws FileNotFoundException {...

thus indicating that it may throw this exception if it can't create the outputstream (for whatever reason). Note that FileNotFoundException is not the best name for the exception in this circumstance, but that's a naming issue you can't deal with.

In fact you will probably want to declare IOException in the main() throws clause above. The different methods you're calling will be declared as throwing variants of this.

Brian Agnew
A: 

FileNotFoundException is not handled in the code. Adding FileOutputStream fout = new FileOutputStream(fileName); between try catch block would solve the problem.

import java.io.*;
public class Red {
    public static void main(String args[]) {

    String fileName = "RedDot.ppm"; 
    try
    {
     FileOutputStream fout = new FileOutputStream(fileName);
     DataOutputStream out = new DataOutputStream(fout);
    }catch(FileNotFoundException fnfExcep){
     System.out.println("Exception Occurred " + fnfExcep.getMessage() );
    }
    System.out.print("P6 1 1 255 ");
        System.out.write(255);
        System.out.write(0);
        System.out.write(0);
        System.out.flush();
    }
}