Java error unreported exception ioexception must be caught or declared to be thrown

Error: filecontent.java:15: unreported exception java.io.IOException; must be caught or declared to be thrown showfile(); ^ filecontent.java:78: unrep...

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that’s what the «throws» keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it’s permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

  1. Demonstration of Unreported IOException
  2. Use try-catch to Catch Unreported IOException
  3. Use the throws Keyword to Eradicate IOException

Resolve Unreported Exception IOException Must Be Caught or Declared to Be Thrown in Java

This tutorial demonstrates another compile time exception saying unreported exception ioexception; must be caught or declared to be thrown. We will also learn about its possible causes and solutions via sample programs.

Demonstration of Unreported IOException

Example Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestClass {

    public static void main(String[] args){
        BufferedReader inputFile = null;
        PrintWriter outputFile = null;
        String inputFileName = "C:\New folder\inputFile.txt";
        String outputFileName = "C:\New folder\outputFile.txt";
        try {
            inputFile = new BufferedReader(new FileReader(inputFileName));
            outputFile = new PrintWriter(new FileWriter(outputFileName));
            String lineOfText = inputFile.readLine();
            while (lineOfText != null) {
                if (lineOfText.contains("x")) {
                    lineOfText = lineOfText.replaceAll("x" + ".*", ""Updated"");
                }
                outputFile.println(lineOfText);
                lineOfText = inputFile.readLine();
            }
        } catch (IOException ioe) {
            System.err.println("Caught IOException: " + ioe.getMessage());
        } finally {
            if (inputFile != null) {
                inputFile.close();//<------This line causes this exception
            }
            if (outputFile != null) {
                outputFile.close();
            }
        }
    }
}

In the code above, we read data from the specified input file; look for the letter x. As soon as it is found, we replace the x and the upcoming text on the same line with the word Updated enclosed in double quotes (" ").

Finally, we close both files (input and output).

The line inputFile.close(); that we are pointing to in the above code example is causing an unreported IOException which must be caught or thrown. What does this mean?

It means the inputFile.close(); is causing the IOException that we can get rid of using the try-catch block (it’s called catching the exception) or using the throws keyword (it’s called exception is thrown). How to do it?

Let’s learn with code examples below.

Use try-catch to Catch Unreported IOException

Example Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestClass {

    public static void main(String[] args){
        BufferedReader inputFile = null;
        PrintWriter outputFile = null;
        String inputFileName = "C:\New folder\inputFile.txt";
        String outputFileName = "C:\New folder\outputFile.txt";
        try {
            inputFile = new BufferedReader(new FileReader(inputFileName));
            outputFile = new PrintWriter(new FileWriter(outputFileName));
            String lineOfText = inputFile.readLine();
            while (lineOfText != null) {
                if (lineOfText.contains("x")) {
                    lineOfText = lineOfText.replaceAll("x" + ".*", ""Updated"");
                }
                outputFile.println(lineOfText);
                lineOfText = inputFile.readLine();
            }
        } catch (IOException ioe) {
            System.err.println("Caught IOException: " + ioe.getMessage());
        } finally {
            if (inputFile != null) {
                try{
                    inputFile.close();
                }catch(IOException ioe){
                    System.err.println("Caught IOException: " + ioe.getMessage());
                }
            }
            if (outputFile != null) {
                outputFile.close();
            }
        }
    }
}

The input file has the following content.

this is x one file
this is x two file
this is x three file

After executing the program, we get an output file containing the content below.

this is "Updated"
this is "Updated"
this is "Updated"

Here, we eliminate the IOException using the try-catch block, where the try statement lets us define a specific block of code that needs to be examined for errors during the execution process.

If any exception occurs at any particular statement within the try block, it will stop execution and jump to the catch block. So, it is strongly advised not to keep the code within the try block that does not throw any exception.

On the other hand, the catch statement permits defining a block of code that needs to be executed if there is any error in the try block. The catch is written right after the try block.

We can also have multiple catch blocks based on how many exceptions we can get in the respective try block.

We can also write a customized message while handling the exception. Now, the question is how these exceptions are handled.

The Java Virtual Machine (JVM) checks whether an exception is handled or not. If it is not, the JVM serves with the default exception handler, which does a few tasks that are listed below:

  • It prints the description of an exception in the program’s output console.
  • It also prints the stack trace in the program’s output console. The stack trace is the methods’ hierarchy where an exception occurred.
  • It results in the program’s termination.

On the other side, the application’s normal flow is maintained if an application programmer has handled the exception, which means the remaining code gets executed.

Use the throws Keyword to Eradicate IOException

Example Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestClass {

    public static void main(String[] args) throws IOException{
        BufferedReader inputFile = null;
        PrintWriter outputFile = null;
        String inputFileName = "C:\New folder\inputFile.txt";
        String outputFileName = "C:\New folder\outputFile.txt";
        try {
            inputFile = new BufferedReader(new FileReader(inputFileName));
            outputFile = new PrintWriter(new FileWriter(outputFileName));
            String lineOfText = inputFile.readLine();
            while (lineOfText != null) {
                if (lineOfText.contains("x")) {
                    lineOfText = lineOfText.replaceAll("x" + ".*", ""Updated"");
                }
                outputFile.println(lineOfText);
                lineOfText = inputFile.readLine();
            }
        } catch (IOException ioe) {
            System.err.println("Caught IOException: " + ioe.getMessage());
        } finally {
            if (inputFile != null) {
                inputFile.close();
            }
            if (outputFile != null) {
                outputFile.close();
            }
        }
    }
}

The content of an input file is as follows.

this is x one file
this is x two file
this is x three file

The output file has the updated content as given below.

this is "Updated"
this is "Updated"
this is "Updated"

This code is the same as the previous section, where we only use the try-catch block to handle the exception. Here, we are using throws to declare an exception; we can also declare multiple exceptions separated by a comma (,).

The throws keyword informs the application programmer that an exception may occur in this method. Remember, the throws keyword is written while defining the function (see in the given example code).

So, it is good and strongly advised that the programmer handle this exception in the code to maintain the normal execution flow. Otherwise, the program will terminate. Let’s understand it via example code.

Copy the following code and run it. Make sure we have an incorrect path for the input file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestClass {

    public static void main(String[] args) throws IOException{
        BufferedReader inputFile = null;
        PrintWriter outputFile = null;
        String inputFileName = "C:\New folder\input.txt";
        String outputFileName = "C:\New folder\outputFile.txt";
        try {
            inputFile = new BufferedReader(new FileReader(inputFileName));
            outputFile = new PrintWriter(new FileWriter(outputFileName));
            String lineOfText = inputFile.readLine();
            while (lineOfText != null) {
                if (lineOfText.contains("x")) {
                    lineOfText = lineOfText.replaceAll("x" + ".*", ""Updated"");
                }
                outputFile.println(lineOfText);
                lineOfText = inputFile.readLine();
            }
        } catch (IOException ioe) {
            System.err.println("Caught IOException: " + ioe.getMessage());
        } finally {
            if (inputFile != null) {
                inputFile.close();
            }
            if (outputFile != null) {
                outputFile.close();
            }
        }
        System.out.println("Continue execution!");
    }
}

OUTPUT:

Caught IOException: C:New folderinput.txt (The system cannot find the file specified)
Continue execution!

We will see the output as given above. The program continues code execution because we have handled the exception.

Now, comment out the try, catch, and finally blocks as follows and rerun the code. Make sure we have an incorrect path for an input file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestClass {

    public static void main(String[] args) throws IOException{
        BufferedReader inputFile = null;
        PrintWriter outputFile = null;
        String inputFileName = "C:\New folder\input.txt";
        String outputFileName = "C:\New folder\outputFile.txt";
        //try {
            inputFile = new BufferedReader(new FileReader(inputFileName));
            outputFile = new PrintWriter(new FileWriter(outputFileName));
            String lineOfText = inputFile.readLine();
            while (lineOfText != null) {
                if (lineOfText.contains("x")) {
                    lineOfText = lineOfText.replaceAll("x" + ".*", ""Updated"");
                }
                outputFile.println(lineOfText);
                lineOfText = inputFile.readLine();
            }
        //} catch (IOException ioe) {
        //    System.err.println("Caught IOException: " + ioe.getMessage());
        //} finally {
            if (inputFile != null) {
                inputFile.close();
            }
            if (outputFile != null) {
                outputFile.close();
            }
        //}
        System.out.println("Continue execution!");
    }
}

The program will terminate the execution as soon as it finds the exception and never reaches the following line of code.

System.out.println("Continue execution!");

This is the reason we handle our declared exceptions. Remember, we can only declare the checked exceptions because the programmer can handle the unchecked exceptions within the code.

Содержание

  1. Resolve Unreported Exception IOException Must Be Caught or Declared to Be Thrown in Java
  2. Demonstration of Unreported IOException
  3. Use try-catch to Catch Unreported IOException
  4. Use the throws Keyword to Eradicate IOException

Resolve Unreported Exception IOException Must Be Caught or Declared to Be Thrown in Java

This tutorial demonstrates another compile time exception saying unreported exception ioexception; must be caught or declared to be thrown . We will also learn about its possible causes and solutions via sample programs.

Demonstration of Unreported IOException

In the code above, we read data from the specified input file; look for the letter x . As soon as it is found, we replace the x and the upcoming text on the same line with the word Updated enclosed in double quotes ( » » ).

Finally, we close both files (input and output).

The line inputFile.close(); that we are pointing to in the above code example is causing an unreported IOException which must be caught or thrown. What does this mean?

It means the inputFile.close(); is causing the IOException that we can get rid of using the try-catch block (it’s called catching the exception) or using the throws keyword (it’s called exception is thrown). How to do it?

Let’s learn with code examples below.

Use try-catch to Catch Unreported IOException

The input file has the following content.

After executing the program, we get an output file containing the content below.

Here, we eliminate the IOException using the try-catch block, where the try statement lets us define a specific block of code that needs to be examined for errors during the execution process.

If any exception occurs at any particular statement within the try block, it will stop execution and jump to the catch block. So, it is strongly advised not to keep the code within the try block that does not throw any exception.

On the other hand, the catch statement permits defining a block of code that needs to be executed if there is any error in the try block. The catch is written right after the try block.

We can also have multiple catch blocks based on how many exceptions we can get in the respective try block.

We can also write a customized message while handling the exception. Now, the question is how these exceptions are handled.

The Java Virtual Machine (JVM) checks whether an exception is handled or not. If it is not, the JVM serves with the default exception handler, which does a few tasks that are listed below:

  • It prints the description of an exception in the program’s output console.
  • It also prints the stack trace in the program’s output console. The stack trace is the methods’ hierarchy where an exception occurred.
  • It results in the program’s termination.

On the other side, the application’s normal flow is maintained if an application programmer has handled the exception, which means the remaining code gets executed.

Use the throws Keyword to Eradicate IOException

The content of an input file is as follows.

The output file has the updated content as given below.

This code is the same as the previous section, where we only use the try-catch block to handle the exception. Here, we are using throws to declare an exception; we can also declare multiple exceptions separated by a comma ( , ).

The throws keyword informs the application programmer that an exception may occur in this method. Remember, the throws keyword is written while defining the function (see in the given example code).

So, it is good and strongly advised that the programmer handle this exception in the code to maintain the normal execution flow. Otherwise, the program will terminate. Let’s understand it via example code.

Copy the following code and run it. Make sure we have an incorrect path for the input file.

We will see the output as given above. The program continues code execution because we have handled the exception.

Now, comment out the try , catch , and finally blocks as follows and rerun the code. Make sure we have an incorrect path for an input file.

The program will terminate the execution as soon as it finds the exception and never reaches the following line of code.

This is the reason we handle our declared exceptions. Remember, we can only declare the checked exceptions because the programmer can handle the unchecked exceptions within the code.

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Источник


posted 16 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

If anyone culd help?? I’m getting this error:
Ch2_Lab.java:53: unreported exception java.io.IOException; must be caught or declared to be thrown
num = Integer.parseInt(keyboard.readLine());
^
Ch2_Lab.java:57: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw new Exception(«Exception: Number cannot be negative»);
^
2 errors


posted 16 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You can only throw checked exceptions from a method if the method declares these exceptions, i.e. :

If you don’t declare the method with «throws» you need to handle the exception within the method. This is because checked exceptions exist to allow the compiler to check that they are properly being handled. Basically the possibility the an operation can fail, and an indication of how it might fail is written into the language to force the coder to handle this possibility.
[ January 25, 2007: Message edited by: Paul Sturrock ]


posted 16 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You are not catching the exceptions being thrown. keyboard.readLine() throws IOException, and you throw just a plain Exception. Then the only catch you consider is a NumberFormatException, though this is never thrown. So all you need is to make sure you catch IOException AND catch Exception (or throw a NumberFormatException instead).

Studying for SCJP 6

Paul Sturrock

Bartender

Posts: 10336

Hibernate
Eclipse IDE
Java


posted 16 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Then the only catch you consider is a NumberFormatException, though this is never thrown.

Actually it is thrown (from Integer.parseInt()). But since it is an unchecked exception you don’t need to handle it.

Shananne DuFrame

Ranch Hand

Posts: 51


posted 16 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Thanks bunches. Got it!!

Подскажите, в чем ошибка?
Не совсем понимаю что он говорит.

Компилятор выдает:
com/javarush/task/task06/task0611/StringHelper.java:11: error: unreported exception java.io.IOException; must be caught or declared to be thrown
String text = R.readLine();
^
com/javarush/task/task06/task0611/StringHelper.java:26: error: unreported exception java.io.IOException; must be caught or declared to be thrown
String text = R.readLine();
^
com/javarush/task/task06/task0611/StringHelper.java:27: error: unreported exception java.io.IOException; must be caught or declared to be thrown
count = Integer.parseInt(R.readLine());
^

package com.javarush.task.task06.task0611;

import java.io.BufferedReader;
import java.io.InputStreamReader;
/* Класс StringHelper*/
public class StringHelper {
    public static String multiply(String s) {
        String result = "";

        BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
        String text = R.readLine();

        StringBuffer sBuffer = new StringBuffer();  // создали объект нашего буфера
        for (int i=0; i<5; i++) {
            sBuffer.append(text);                   // использовали команду, которая добавляет строку text к концу строки, имеющейся в буфере
        }
        result = sBuffer.toString();                // в result вывели то, что накопилось в буфере
        return result;

    }

    public static String multiply(String s, int count) {
        String result = "";

        BufferedReader R = new BufferedReader(new InputStreamReader(System.in));
        String text = R.readLine();
        count = Integer.parseInt(R.readLine());

        StringBuffer sBuffer = new StringBuffer();  // создали объект нашего буфера
        for (int i=0; i<count; i++){
            sBuffer.append(text);                   // использовали команду, которая добавляет строку text к концу строки, имеющейся в буфере
        }
        result = sBuffer.toString();                // в result вывели то, что накопилось в буфере
        return result;
    }

    public static void main(String[] args) {

    }
}


Recommended Answers

Exceptions which are not RuntimeExceptions must be handled explicitly. They cannot be ignored. A method where an Exception may occur can either declare it to be thrown, or catch it. You catch an exception by using something like:

try
{
    methodThatMightThrowExceptionA();
}
catch(ExceptionA e)
{
    whatIWantToDoIfExceptionAHappens();
} …

Jump to Post

Next time, please copy & paste the error shown by runtime. Your assumption may be correct, but it may be incorrect under certain circumstances.

If you look at the method in Logger class, there is a variable this.input inside the method. The variable input and this.input are not the same. …

Jump to Post

There’s no need to write your own logger. There are frameworks available for that.

If you’re interested, you might want to take a look at these links:

  • java.util.logging (JUL)

Jump to Post

That looks different from what you posted earlier.

Anyway, passing null value, but later concatenating it with String won’t cause the NPE. You still have not posted the exact exception/error you got from running your program… What exactly error it shows?

If you have already declared the variable, then what …

Jump to Post

Nope, I’m talking about parser.getCommand() which may return null or something is wrong in there. The NPE could actually comes from using null to call getCommandWord(). That’s my suspicious.

By the way, the exact error should also tells you which line the error occurs. If you are not sure, add …

Jump to Post

All 17 Replies

Member Avatar

10 Years Ago

Exceptions which are not RuntimeExceptions must be handled explicitly. They cannot be ignored. A method where an Exception may occur can either declare it to be thrown, or catch it. You catch an exception by using something like:

try
{
    methodThatMightThrowExceptionA();
}
catch(ExceptionA e)
{
    whatIWantToDoIfExceptionAHappens();
}

You know that ExceptionA might be thrown from methodThatMightThrowExceptionA because its declaration includes throws ExceptionA. And if you don’t want to catch your exception, then you can do that too. Like this:

public void methodThatDoesNotCatch() throws ExceptionA
{
    methodThatMightThrowExceptionA();
}

This method does not have to catch the exception because it is declared to throw the exception, but now anyone who calls methodThatDoesNotCatch() will have to deal with ExceptionA somehow. This is all for the purpose of keeping track of where exceptions might come from and who is responsible for recovering from exceptions. Of course java.lang.RuntimeException and its subclass exceptions are exempt from this rule; they can be thrown anywhere with no requirements to declare or catch them.

So when you see that an exception must be caught or declared to be thrown, that is what it is talking about.

Edited

10 Years Ago
by bguild

Member Avatar

10 Years Ago

I have followed your explanation, and the program compiled, but now it is throwing a nullpointerexception error in the main class Game:

boolean finished = false;
        while (! finished) {
            Command command = parser.getCommand();
            String input = command.getCommandWord() + command.getSecondWord();
            logger.logToFile(input); //the error
            finished = processCommand(command);

        }
        logger.closeStream();
        System.out.println("Thank you for playing.  Good bye.");
}

i have added try and catch for both the writing and closing of the file in the logger class. 

from what i understand about the error, it means that I am passing a null to the logger.lotToFile(input) method, but not sure why!

thank you for the help!

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

Next time, please copy & paste the error shown by runtime. Your assumption may be correct, but it may be incorrect under certain circumstances.

If you look at the method in Logger class, there is a variable this.input inside the method. The variable input and this.input are not the same. The input is a local variable seen by the method. The this.input is the class variable that can be seen by the whole class. Have you ever declared the class’s variable called input in the class?

Edited

10 Years Ago
by Taywin

Member Avatar

Member Avatar

10 Years Ago

Taywin: I still dont get it! I have declared input in the class! not sure what to do,,, :(

Member Avatar

10 Years Ago

thanks tux4life! as I have worked with the Logger now, I think I will continue with it,,,

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

This is your current class…

public class Logger {
  private BufferedWriter out;
  public Logger() throws IOException {
    fw = new FileWriter("logfile.txt");
    bw = new BufferedWriter(fw);
  }

  public void logToFile(String input) throws IOException {
    this.input = input;   // <--- Where did you declare 'input' variable of the class?
    bw.write("User Input: " + input + "n");
  }

  public void closeStream() {
    bw.close();
  }
}

PS: This is not JavaScript that you can simply intialize object/class’s variable on the fly.

Edited

10 Years Ago
by Taywin

Member Avatar

10 Years Ago

this is the source code for logger:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Write a description of class Logger here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Logger
{
    // instance variables - replace the example below with your own
    private BufferedWriter bw;
    private String input;  //declared in here


    /**
     * Constructor for objects of class Logger
     */
    public Logger() throws IOException
    {
        //
        FileWriter fw = new FileWriter("logfile.txt");

        //
        BufferedWriter bw = new BufferedWriter(fw);


    }

    /**
     * 



     */
    public void logToFile(String input) 
    {
        this.input = input;
        try
        {

            bw.write("User Input:  " + input + "n");
            // put your code here
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
    }


    public void closeStream()
     {
        try
        {
        bw.close();
        }
        catch (IOException ioe)
        {
        ioe.printStackTrace();
        }
    }
}

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

That looks different from what you posted earlier.

Anyway, passing null value, but later concatenating it with String won’t cause the NPE. You still have not posted the exact exception/error you got from running your program… What exactly error it shows?

If you have already declared the variable, then what getCommand() returns?

Command command = parser.getCommand();

Is it possible that the method returns null value?

Member Avatar

10 Years Ago

the exact error is:
java.lang.NullPpointerException:
null

Command command = parser.getCommand(); returns an object command of class Command, and getCommandWord() and getSecondWord() return strings. They shouldnt be returning null as the program was working before adding the logger bit!

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

Nope, I’m talking about parser.getCommand() which may return null or something is wrong in there. The NPE could actually comes from using null to call getCommandWord(). That’s my suspicious.

By the way, the exact error should also tells you which line the error occurs. If you are not sure, add System.out.println() to see where your program stops at…

public void logToFile(String input) {
  System.out.println("In logToFile()");
  this.input = input;
  try {
    System.out.println("In try");
    bw.write("User Input: " + input + "n");
    System.out.println("Pass the try");
  // put your code here
  }
  catch (IOException ioe) {
    System.out.println("Failed, in IOException");
    ioe.printStackTrace();
  }
  catch (Exception e) {  // I add this to catch all other Exception
    System.out.println("Unknow exception thrown!");
    e.printStackTrace();
  }
}


boolean finished = false;
System.out.println("Start checking");
while (! finished) {
  System.out.println("Not done");
  Command command = parser.getCommand();
  System.out.println("Got command: "+(command==null ? "NULL" : "OK"));
  String input = command.getCommandWord() + command.getSecondWord();
  System.out.println("Got input: "+(input==null ? "NULL" : "OK"));
  logger.logToFile(input); //the error
  System.out.println("Logged successfully");
  finished = processCommand(command);
  System.out.println("Recheck again");
}
System.out.println("Closing the stream");
logger.closeStream();
System.out.println("Closed the stream");
System.out.println("Thank you for playing. Good bye.");

PS: You should use this System.out.println() technique to debug your code if you do not use any luxurious IDE or you don’t know how to use the debug feature in an IDE.

Edited

10 Years Ago
by Taywin

Member Avatar

10 Years Ago

it is a very smart way! i added a print out for the "input" string, i got this:

You are outside the main entrance of the university.
Exits:  south east west
sTARET CHECKING
NOT DONE
> go south
got command: OK
Got input: OK
gosouth

the error line:

Command command = parser.getCommand();
            System.out.println("got command: "+ (command==null ? "NULL" : "OK"));
            String input = command.getCommandWord() + command.getSecondWord();
            System.out.println("Got input: "+(input==null ? "NULL" : "OK"));
            System.out.println(input);
            logger.logToFile(input); // here is the error
            System.out.println("Logged successfully");
            finished = processCommand(command);
            System.out.println("Recheck again");

even when I removed logger.logToFile(input); and kept the .close(); line, i got the same error!

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

So does your main class initiate the Logger instance?

Member Avatar

10 Years Ago

no, the Logger instance wasnt initiated @_@'' !!! thanks Taywin :)

for some reason, I get "unknown exception thrown" should I get red of 
catch (Exception e) {
.....
}
? or something else went wrong? I still dont know where the file is saved!

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

So what stack trace is printed? Also, does your program have permission to create/write a file in the folder/directory your program is running?

Member Avatar

10 Years Ago

is this the stack trace:
"t __SHELL1.run(__SHELL1.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at bluej.runtime.ExecServer$3.run(ExecServer.java:725)" ?

I dont know if it has the permission! didnt do anything about that,,,

Member Avatar


Taywin

312



Posting Virtuoso


10 Years Ago

Just take a look at BufferedWriter class… There is no such a method write(String) but rather write(String, int, int)

PS: When you ask others to help you debugging, please post all the exception thrown from your program. It is not easy and could be inaccurate to assume what’s going wrong in your program. Only code is not enough. Your own analysis is even worse. If your analysis is correct, you would not be asking questions…


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • Java error unable to load resource
  • Java error script вк
  • Java error release version 5 not supported ошибка
  • Java error release version 5 not supported как убрать
  • Java error reading zip end header not found