Poliquin
Poliquin

Reputation: 2987

Error messages with Java Swing

I have a query on handling error conditions with Java Swing.

I am using Netbeans to develop a simple Java Swing app. It is to load in a text file, then run calculation based on the numbers found in the text file. The main Swing class holds the JFrames and JPanels.

I have the file loading code as a separate class file. It returns the number of lines read and a List of numbers back to the main Swing app.

I realised that if the file reading fails (i.e. try -> catch (Exception ex)), the entire app will crash. What's the best way to handle errors resulting from my scenario above? That is to say, the file loading code crashes and I don't want the entire program to crash. I want the program to say the file is corrupted and wait for user to load new file.

Any thoughts?

Yakult

Upvotes: 3

Views: 11626

Answers (3)

underscore
underscore

Reputation: 6887

yeah the problem is with your IO reading concept the while loop is reading to the end of the file and so on.. to prevent that u can use a buffered reader and use this code

String line = null
while((line = reader.readLine())!= null) {
// do stuf
}

if you are having this problem with processing the read line all you need is to create a exception class of your own by extending Exception class and throw that exception in your catch block after setting the message to your custom exception class you can set that message in to

 JOptionPane.showMessageDialog(null,"message here"); //showMessageDialog is a static method

ok

Upvotes: 1

ewok
ewok

Reputation: 21443

when you catch the exception, run:

JOptionPane.showMessageDialog("File is corrupted. Please select a new file.");

Then display the file dialog again.

It's probably best to do this as a loop that continues while the the file is not valid. If there is a corruption, then rather than throwing an exception, set a boolean flag and loop as long as the flag is set. That way, when a good file is found, the while loop will terminate.

Example:

public static void main(String[] args){
    boolean goodFile = false;

    while (!goodFile){
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog();

        goodFile = processFile(chooser.getSelectedFile());
    }
}

private boolean processFile(File file){
    //do you stuff with the file

    //return true if the processing works properly, and false otherwise    
}

Upvotes: 6

GingerHead
GingerHead

Reputation: 8230

You just catch the exception and put condition in the catch block. If the file contains other content that your application is intended to handle then you could call your method which will re-handle another file.

The main handling of your new process of the new file manipulation will start from your catch block. So in this way you are using java thrown exception to restart your application in a brand new way other than relaunching your app from the zero level.

Upvotes: 0

Related Questions