简体   繁体   中英

Java Exception printing twice

I know the exception is kind of pointless, but I was trying to learn how to use / create exceptions so I used this. The only problem is for some reason my error message generated by my exception is printing to console twice.

import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner;

public class Project3
{

  public static void main(String[] args)
  {
    try
    {
      String inputFileName = null;
      if (args.length > 0)
        inputFileName = args[0];
      File inputFile = FileGetter.getFile(
          "Please enter the full path of the input file: ", inputFileName);

      String outputFileName = null;
      if (args.length > 1)
        outputFileName = args[1];
      File outputFile = FileGetter.getFile(
          "Please enter the full path of the output file: ", outputFileName);

      Scanner in = new Scanner(inputFile);
      PrintStream out = new PrintStream(outputFile);
      Person person = null;

      // Read records from input file, get an object from the factory,
      // output the class to the output file.
      while(in.hasNext())
      {
        String personRecord = in.nextLine();

        person = PersonFactory.getPerson(personRecord);

        person.display(); 

        person.output(out);
      }
    } catch (Exception e)
    {
      System.err.println(e.getMessage());
    }
  }

}





import java.util.Scanner;

class Student extends Person
{
  private double gpa;

  public Student()
  {
    super();
    gpa = 0.0;
  }

  public Student(String firstName, String lastName, double gpa)
  {
    super(firstName, lastName);
    this.gpa = gpa;
  }

  public String toString(){
   try{
        if (gpa >= 0.0 && gpa <= 4.0){
            return super.toString() + "\n\tGPA: " + gpa;
        }
        else {
            throw new InvalidGpaException();
        }
    }
   catch (InvalidGpaException e){
       System.out.println(e);
       return super.toString() + "\n\tGPA: " + gpa;
   }
  }

  public void display()
  {
    System.out.println("<<Student>>" + this);
  }

  @Override
  public void input(Scanner in)
  {
    super.input(in);

    if (in.hasNextDouble())
    {
      this.gpa = in.nextDouble();
    }
  }

  class InvalidGpaException extends Exception {
    public InvalidGpaException() {
        super("Invalid GPA: " + gpa);
      }
  }
}

This is my console readout. Not sure what's causing the exception to print twice.

project3.Student$InvalidGpaException: Invalid GPA: -4.0
<< Student>>
        Id: 2        Doe, Junior
        GPA: -4.0
project3.Student$InvalidGpaException: Invalid GPA: -4.0

edit: The main code is on the top. The input is a file designated by the user. What I shown right here is my console printout, not what is returned to the output file. The output file shows the exact same thing minus the error message. The Error message from the exception (which I know is not necessary) is only printed to the console. I don't see where I'm printing it twice.

My guess is that your Person.output() method has a call to toString() in it, which will print the exception before returning the proper string, which doesn't show up because you're outputting it to out .

E: If you want my deduction, here it is: The first error message and normal message are printed out within the call to display() , as it should be. Immediately after that is the output() call, which by the name I guess is meant to do what display() does, except to a file. However, you forgot that the exception is printed directly to System.out , so it appears in the console, while the string that toString() actually returns is written to the file.

What is your main ? what is your INPUT.. Change your exception to something different.

Where are you printing this data ?

<< Student>>
        Id: 2        Doe, Junior
        GPA: -4.0

Are you sure you aren't calling person.toString() twice ?

My guess is that you are calling toString somewhere in the code you have not shown to us.

Putting in a Thread.dumpStack(); in the toString implementation should tell you from where.

Try changing this:

System.out.println(e);
   return super.toString() + "\n\tGPA: " + gpa;

to

System.out.println(e);

(Or something similar)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM