Search code examples
javafileexceptionfileopendialog

Throw and Catch Custom Exception


I have a method to load a customer file by choosing it from the File Open Dialog Box and it works, except for when I click the Cancel button. It still loads the selected file even if I press the Cancel button. I want to load a Custom Exception if I click the Cancel Button. Any help on how to implement the Custom Exception in my method please? Thanks

 private void loadCustomerActionPerformed(java.awt.event.ActionEvent evt) {
   Customer customerfile = null;
   try {

     final JFileChooser chooser = new JFileChooser("Customers/");
     int chooserOption = chooser.showOpenDialog(null);
     chooserOption = JFileChooser.APPROVE_OPTION;

     File file = chooser.getSelectedFile();
     ObjectInputStream in = new ObjectInputStream(
       new FileInputStream(file)
     );

     customerfile = (Customer) in .readObject();

     custnameTF.setText(customerfile.getPersonName());
     custsurnameTF.setText(customerfile.getPersonSurname());
     custidTF.setText(customerfile.getPersonID());
     custpassidTF.setText(customerfile.getPassaportID());
     customertellTF.setText(customerfile.getPersonTel());
     customermobTF.setText(customerfile.getPersonMob());
     consnameTF.setText(customerfile.getConsultantname());
     conssurnameTF.setText(customerfile.getConsultantsurname());
     considTF.setText(customerfile.getConsulid());

     in .close();

   } catch (IOException ex) {
     System.out.println("Error Loading File" + ex.getMessage());
   } catch (ClassNotFoundException ex) {
     System.out.println("Error Loading Class");
   } finally {
     System.out.println("Customer Loaded");
   }

 }

Solution

  • Make your method declaration to trow your Exception:

    private void loadCustomerActionPerformed(java.awt.event.ActionEvent evt)
        throws CustomException {
    

    You are giving always APPROVE_OPTION to chooserOption:

     chooserOption = JFileChooser.APPROVE_OPTION; 
    

    You must make dialog button listener to modify this variable and add a condition:

    if (chooserOption == JFileChooser.APPROVE_OPTION) {
        // load file
    } else {
        throw new CustomException("ERROR MESSAGE");
    }
    

    And your CustomException Class must look like:

    class CustomExceptionextends Exception {
        public CustomException(String msg) {
            super(msg);
        }
    }