0

I am trying to create a Java application using Netbeans 8.2 for a uni project. I'm having an issue after creating a JFrame for adding some data to the database.

NetBeans highlights the final statement ujc.create(u2); in the code segment below with the following error message:

Unreported exception PreexistingEntityException; must be caught or declared to be thrown

Can someone advise what I need to do to fix this issue? I have no idea what I'm doing wrong.

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
   {
      Users u2 = new Users();
      u2.setEmployeeno(jTextField1.getText());
      u2.setFirstname(jTextField2.getText());
      u2.setSurname(jTextField3.getText());
      
      EntityManagerFactory emf = Persistence.createEntityManagerFactory(
              "BatteryManagementSystemPU");
      UsersJpaController ujc = new UsersJpaController(emf);
      ujc.create(u2);
   }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dan
  • 31
  • 3

1 Answers1

0

The create(...) method call here can fail, so we need to allow for that failure by surrounding the method with a try/catch block:

try
{
    ujc.create(u2);
}
catch(PreexistingEntityException e)
{
    System.err.println("Caught PreexistingEntityException: " + e.getMessage());
}

You can find great information on the topic at the official tutorial page: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

The other option is to throw the error, however, the calling method for jButton1ActionPerformed will now need to catch the error instead, so it's better not to use this solution in most cases if you are unsure on what is happening:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws PreexistingEntityException
{
    ....

You can find more information on throwing an error here: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html

sorifiend
  • 5,927
  • 1
  • 28
  • 45
  • Thank you, that seems to have worked. What was confusing me was that I built a project that was more or less exactly the same however it never threw up that error message. – Dan Mar 14 '22 at 02:37
  • It would be interesting to see what the difference is. Either you called a method that didn't need to catch/throw an error, or as a guess you may have hit Alt+Enter in Netbeans by mistake and it could have added the `throws PreexistingEntityException` to the main method etc, and assuming an error is never encountered the code would work as expected. – sorifiend Mar 14 '22 at 02:42