Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2007

Tip: Looking for answers? Try searching our database.

exception

Thread view: 
Art Cummings - 30 Nov 2007 03:28 GMT
Good evening all,

I'm taking a java class and as one of the final assignments, we've got to
write a program that uses a gui with buttons.  We've got to use a function
that adds records.  I've got this being handled by a button but i'm getting
an error that I need a throws exception.  As luck would have it, the
instructor never covered this aspect of Java but I did find an example on
google.  The problem i'm having is understanding how to use it.  Since my
button processes the code it seems like the exception handling needs to be
there.  I don't know of another way to call the button other than using the
listener, that triggers the event when the button is pressed.  At this
point, i'm stuck.  Any insight about how to do this, is appreciated.  This
is an introductory java class so.

The error message I get.
¼§ÏStudentAddWindow.java:92: exception java.io.IOException is never thrown
in body of corresponding try statement

private class addButtonListener implements ActionListener
{

public void actionPerformed(ActionEvent e)

{

try
{ String name;
} catch (IOException x)

{

FileWriter swriter = new FileWriter("c:\\studname.txt",true);
JOptionPane.showMessageDialog(null,"The file could not be written.");
//name = StudentTextField.getText();
FileWriter swriter = new FileWriter("c:\\studname.txt",true);
//FileWriter gwriter = new FileWriter("c:\\grades.txt",true);
PrintWriter outputFile2 = new PrintWriter(gwriter);
//PrintWriter outputFile= new PrintWriter(swriter);
outputFile.println(name);
//outputFile2.println("0,0,0");
outputFile.close();
//outputFile2.close();
StudentTextField.setText("");

}

Thanks

Art
Eric Sosman - 30 Nov 2007 03:39 GMT
> [...]
> The error message I get.
[quoted text clipped - 12 lines]
> } catch (IOException x)
> [...]

    Well, okay, why do you thing `String name;' is going
to throw an IOException?  The whole inside of the try block
does nothing at all -- it declares a variable `name' that
can refer to String objects, but never uses it and never
does anything -- so there's no way an IOException can ever
be thrown.  Why are you trying to catch something that
cannot exist?

Signature

Eric Sosman
esosman@ieee-dot-org.invalid

Art Cummings - 30 Nov 2007 04:19 GMT
My apologies, the code for the throw was assumed.  I've included it here.

Thanks

public void actionPerformed(ActionEvent e)
{
try
{

addingStudent();
}
catch (IOException x)

{
String name;
name = StudentTextField.getText();
FileWriter swriter = new FileWriter("c:\\studname.txt",true);
FileWriter gwriter = new FileWriter("c:\\grades.txt",true);
PrintWriter outputFile2 = new PrintWriter(gwriter);
PrintWriter outputFile= new PrintWriter(swriter);
outputFile.println(name);
outputFile2.println("0,0,0");
outputFile.close();
outputFile2.close();
StudentTextField.setText("");

}

>> [...]
>> The error message I get.
[quoted text clipped - 20 lines]
> be thrown.  Why are you trying to catch something that
> cannot exist?
RedGrittyBrick - 30 Nov 2007 10:48 GMT
> My apologies, the code for the throw was assumed.  I've included it here.
>
[quoted text clipped - 10 lines]
>
> }

Maybe its simpler to show how I think it should be done.

public void actionPerformed(ActionEvent e) {
    // Dear tutor, grill student re spoonfed solution from usenet.
    try {
        String name = StudentTextField.getText();

        FileWriter swriter = new FileWriter("c:\\studname.txt",true);
        PrintWriter outputFile= new PrintWriter(swriter);
        outputFile.println(name);
        outputFile.close();

        FileWriter gwriter = new FileWriter("c:\\grades.txt",true);
        PrintWriter outputFile2 = new PrintWriter(gwriter);
        outputFile2.println("0,0,0");
        outputFile2.close();

        StudentTextField.setText("");

    } catch (IOException x) {
        System.out.println("Unable to add student - " + x.getMessage());
        JOptionPane.showMessageDialog(frame, x.getMessage, "AppName",
                JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }
}

Untested, caveat emptor.
Lew - 30 Nov 2007 11:28 GMT
> Maybe its simpler to show how I think it should be done.
>
[quoted text clipped - 24 lines]
>
> Untested, caveat emptor.

All that I/O - could end up being a lengthy process, ergo, a candidate to move
off the EDT.

Signature

Lew

RedGrittyBrick - 30 Nov 2007 16:29 GMT
>> Maybe its simpler to show how I think it should be done.

[snip]

> All that I/O - could end up being a lengthy process, ergo, a candidate
> to move off the EDT.

Ooh yes ... let me dig myself a little deeper ...

Art, please avert your gaze ...

public void actionPerformed(ActionEvent e) {
    // Blindly copying usenet may be hazardous to your education.

    frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    final String name = StudentTextField.getText();

    new SwingWorker<Void, Void>() {
        private IOException pendingException;

        @Override
        protected Void doInBackground() {  // not EDT
            try {

                FileWriter swriter = new FileWriter(
                    "c:\\studname.txt",true);
                PrintWriter outputFile= new PrintWriter(swriter);
                outputFile.println(name);
                outputFile.close();

                FileWriter gwriter = new FileWriter(
                     "c:\\grades.txt",true);
                PrintWriter outputFile2 = new PrintWriter(gwriter);
                outputFile2.println("0,0,0");
                outputFile2.close();

            } catch (IOException x) {
                pendingException = x;
                System.out.println("Unable to add student - "
                       + pendingException.getMessage());
            }
        }

        @Override
        protected void done() { // on EDT
            frame.setCursor(null);
            if (pendingException == null) {
                StudentTextField.setText("");
            } else {
                JOptionPane.showMessageDialog(
                       frame,
                       "Unable to add student - "
                       + pendingException.getMessage,
                       "AppName",
                       JOptionPane.ERROR_MESSAGE);
                System.exit(1); // or let 'em retry?
            }
        }
    }.execute();
}

Untested, undoubtedly borken in many ways, ++caveat emptor--;

(Also IMO needs refactoring into smaller methods/classes to tame
indentation a bit)
Nigel Wade - 30 Nov 2007 16:52 GMT
> All that I/O - could end up being a lengthy process, ergo, a candidate to move
> off the EDT.

and it might be a good idea to check if it actually succeeded. According to the
API PrintWriter.println does not throw any IOException if it fails.

I'll leave it as an exercise for the OP to figure out how to handle this
eventuality.

Signature

Nigel Wade, System Administrator, Space Plasma Physics Group,
           University of Leicester, Leicester, LE1 7RH, UK
E-mail :    nmw@ion.le.ac.uk
Phone :     +44 (0)116 2523548, Fax : +44 (0)116 2523555

Art Cummings - 30 Nov 2007 14:28 GMT
Thanks red, I see that I had the code somewhat reveresed.  It's alot clearer
now how to use the try statement.

Art Cummings

>> My apologies, the code for the throw was assumed.  I've included it here.
>>
[quoted text clipped - 39 lines]
>
> Untested, caveat emptor.
Andrew Thompson - 30 Nov 2007 04:33 GMT
> Good evening all,

My evening is better when I do not need to chase
after multi-posters asking them to 'kindly refrain
from multi-posting in future'.

(X-post to c.l.j.g./h., w/ f-u to c.l.j.h. only)

--
Andrew T.
Art Cummings - 30 Nov 2007 04:41 GMT
my apologies,

any suggestions on the code problem?
>> Good evening all,
>
[quoted text clipped - 6 lines]
> --
> Andrew T.
Andrew Thompson - 30 Nov 2007 09:46 GMT
>my apologies,

Sure (I'll take that to read "it won't happen again" which
is all that interests me).

>any suggestions on the code problem?

Roedy and Eric have offered some useful advice if you
understand how to use it - you might research their
suggestions further.

I also recommend posting SSCCE code, as it helps
people to see the exact problem, and avoids the need
(largely) to provide later snippets of code.  

You can find more info. on the SSCCE here.
<http://www.physci.org/codes/sscce.html>

Another thing I recommend is to 'do as the locals do'
and post 'in-line with trimming' as myself, Eric and
Roedy have done, rather than 'top-post' replies.

Signature

Andrew Thompson
http://www.physci.org/

Art Cummings - 30 Nov 2007 14:34 GMT
Thanks Andrew

I've read the sscce doc and will comply in future post.

Art Cummings

>>my apologies,
>
[quoted text clipped - 17 lines]
> and post 'in-line with trimming' as myself, Eric and
> Roedy have done, rather than 'top-post' replies.
Roedy Green - 30 Nov 2007 07:51 GMT
On Thu, 29 Nov 2007 22:29:34 -0500, "Art Cummings"
<aikiart7@gmail.com> wrote, quoted or indirectly quoted someone who
said :

>try
>{ String name;
>} catch (IOException x)

the pattern is

try {

code that does IO .

}

catch ( IOExeception e )

{
Code to deal with the IO screwing up.

}

see http://mindprod.com/jgloss/exception.html
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Art Cummings - 30 Nov 2007 14:35 GMT
Thanks Roedy,

I'm starting to understand how to use try.

Art Cummings
> On Thu, 29 Nov 2007 22:29:34 -0500, "Art Cummings"
> <aikiart7@gmail.com> wrote, quoted or indirectly quoted someone who
[quoted text clipped - 20 lines]
>
> see http://mindprod.com/jgloss/exception.html
rossum - 30 Nov 2007 13:10 GMT
>Good evening all,
>
[quoted text clipped - 9 lines]
>point, i'm stuck.  Any insight about how to do this, is appreciated.  This
>is an introductory java class so.

[snip code]

If you want to understand exceptions further then you can read the Sun
tutorial at:
 http://java.sun.com/docs/books/tutorial/essential/exceptions/

In general the Sun tutorials are worth looking at if there is a part
of Java you do not understand.

You could also try experimenting on your own with something like:

public class ExceptionTest {

   public static void thisThrows() {
       // Just throw an exception
       throw new Exception("this process has failed because your " +
                      "computer is full of instant mashed potato.");
   }

 
   public static void main(String[] args) {

       try {
           thisThrows();
           System.out.println("We are here.");
       }
       catch (Exception ex) {
           System.out.println("Exception thrown: " +
                              ex.getMessage());
       }      
       System.out.println("Finished.");
    }
}

Yes, I know that will not compile, getting it to compile is part of
the learning process (yes, I used to be a teacher).

For extra credits, predict whether or not the "We are here" message
will be printed before you run the code.

rossum
Art Cummings - 30 Nov 2007 15:28 GMT
Thanks Rossum,

This was a good reference.

Art Cummings

>>Good evening all,
>>
[quoted text clipped - 52 lines]
>
> rossum


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.