Exception Catching

I was wondering what strategies people use to know what exceptions to try and catch? I would like to be able to know what potential exceptions may be thrown by a method or any method it calls etc.
For example I was recently working with DefaultMutableTreeNode.insertNodeInto() method, and got the following: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
at java.util.Vector.insertElementAt(Vector.java:551)
at javax.swing.tree.DefaultMutableTreeNode.insert(DefaultMutableTreeNode.java:177)
at javax.swing.tree.DefaultTreeModel.insertNodeInto(DefaultTreeModel.java:218)
at CheckTree.CheckTreeModel.addNode(CheckTreeModel.java:88)
Now I can look up Vector.insertElementAt() and see what exceptions it could potentially raise. However if I look @ insertNodeInto() in the JavaDocs, it doesn't list any potential exceptions that may be raised, nor does it tell me that it uses Vector.insertElementAt().
Since A. I don't always have all the source code I need to dig through everything I call to see what may cause a problem,
and B. I don't want to have to go through 3000+ lines of source code just to go, oh look someMethod() can raise a DivideByZero exception! I better be prepared to catch it in my function 6 calls up the ladder.
So I'm guessing there is a happy medium when it comes to knowing what to look for.
I know a large part of good code it is making sure your passing sane arguments in your method calls, but when working with new API's it's not always easy to tell what will end up being sane and logical and what will be inappropriate garbage. (Especially with how lacking the JavaDocs can be).
So like I said I'm wondering what strategies work well for people?

OKAY Let's take a look at a quote from the first post.
For example I was recently working with DefaultMutableTreeNode.insertNodeInto() method, and got the following: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 > 0
at java.util.Vector.insertElementAt(Vector.java:551)
at javax.swing.tree.DefaultMutableTreeNode.insert(DefaultMutableTreeNode.java:177)
at javax.swing.tree.DefaultTreeModel.insertNodeInto(DefaultTreeModel.java:218)
at CheckTree.CheckTreeModel.addNode(CheckTreeModel.java:88) You all should be able to recognize a call stack printed in resoponse to an unhandled exception.
Let's take a look at the line in bold. Yes I was mistaken about the object calling insertNodeInto().
But there is a lot of useful information in the callstack, a quick inspection of the callstack reveals
A. the insertNodeInto called was a method of DefaultTreeModel.
B. The exception was raised in insertElementAt()
C. insertElementAt() is called by DefaultMutableTreeNode.insert() which is called by DefaultTreeModel.insertNodeInto().
Here is a direct copy of DefaultTreeModel,insertNodeInto() java doc:
insertNodeInto
public void insertNodeInto(MutableTreeNode newChild,
MutableTreeNode parent,
int index)Invoked this to insert newChild at location index in parents children. This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.
notice a lack of mention of "ArrayIndexOutOfBoundsException" There is a very simple reason for this.
It is because the exception is raised not by insertNodeInto, but by insertElementAt().
I am not stating that the documentation for insertNodeInto() is wrong. It is merely not warning me that I may get an exception generated by a method called my a method it itself falls. For which I do not blame it, because insertNodeInto does NOT directly raise the exception.
I was simply asking what people do to handle exceptions that are generally unforseeable.

Similar Messages

  • How to get details about Exception catched in Exception branch of the Block

    Hello Experts,
    Is it possible to get details about Exception catched in Exception branch of the Block in Integration Process (BPM)?
    In the Exception branch System Error is catched, but from time to time different type of System Errors are happening during sync call to WebService - Connection Timeout, Connection Refused, UnknownHost, etc.
    So the task is somehow to map the type of System Error to the response. I was trying to create a mapping using as source the message which is coming from the Adapter after the sync call, but the mapping is failing with "No Source Payload" error.
    Maybe the description is somewhere in Header or Dynamic configuration?
    Or it is possible to access it somehow with JAVA-maping?
    Thanks for your help!

    Hey,
          the message from the exception can be utilized by using alerts(in order to mail,sms r fax). but otherwise its not possible using mappings or container.
    check this link for alert configuration.
    /people/michal.krawczyk2/blog/2005/09/09/xi-alerts--step-by-step

  • Exception catching, avoiding (sometimes)

    hello,
    i use forte for java and each time i use methods that either read or write to/from a stream without the try catch quotes, i get an error
    Test_Sum.java [58:1] unreported exception java.io.IOException; must be caught or declared to be thrown
    i understand that it is good convention to use the try/catch handlers and do it when writing production code but at times when one just wants to test something, this gets annoying. even some of the tutorial examples do not use these. how do i force the exception catching requirement off?
    thanks in advance jiri

    catch the exceptions you want, and have all methods that might throw an exception declare
    throws Exception
    or
    put everything in a method in 1 try catch block
    mymethod()
      try
      catch (Exception e)

  • IO or FileNotFound Exception catch does not work for getRequestDispatcher

    Hi,
    I am trying to catch IOException / FileNotFoundException in my servlet for the call to getRequestDispatcher().forward(request, response) and than throw user define exception from that catch. I am using JDeveloper 10.1.3. Some how the control is not going to catch block when the file does not exist to forward. But instead JDeveloper is throwing its own exception with error mesg
    NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException:
    and browser shows standard 404 File Not Found error page. I would rather have want to display appropriate error page. Here is my code:
    try
    System.out.println("in try");
    context.getRequestDispatcher("/" + currentScreen).forward(request, response);
    System.out.println("after try");
    catch(java.io.IOException fileNotFoundEx)
    System.out.println("runtime exception");
    logger.error(CLASS_OBJECT, "f n f "+RootException.getStackTraceString(fileNotFoundEx));
    throw new RequestHandlerException("requestHandlerError", fileNotFoundEx);
    Here is the output on console:
    06/08/01 10:35:18 in try
    2006-08-01 10:35:18.921 NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.io.FileNotFoundException: F:\JavaProjects\WorkspaceDev\CorAssessment\web\jsp\assessment_multi_view1.jsp (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at oracle.jsp.provider.JspFilesystemResource.fromStream(JspFilesystemResource.java:150)
    at oracle.jsp.parse.XMLUtil.getFromStream(XMLUtil.java:228)
    at oracle.jsp.runtimev2.JspPageCompiler.compilePage(JspPageCompiler.java:341)
    at oracle.jsp.runtimev2.JspPageInfo.compileAndLoad(JspPageInfo.java:610)
    at oracle.jsp.runtimev2.JspPageTable.compileAndServe(JspPageTable.java:634)
    at oracle.jsp.runtimev2.JspPageTable.service(JspPageTable.java:370)
    at oracle.jsp.runtimev2.JspServlet.internalService(JspServlet.java:478)
    at oracle.jsp.runtimev2.JspServlet.service(JspServlet.java:401)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    at com.evermind.server.http.ServletRequestDispatcher.unprivileged_forward(ServletRequestDispatcher.java:270)
    at com.evermind.server.http.ServletRequestDispatcher.access$100(ServletRequestDispatcher.java:42)
    at com.evermind.server.http.ServletRequestDispatcher$2.oc4jRun(ServletRequestDispatcher.java:204)
    at oracle.oc4j.security.OC4JSecurity.doPrivileged(OC4JSecurity.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:209)
    at com.nexcom.cor.manager.ViewManager.forwardToNextScreen(ViewManager.java:142)
    at com.nexcom.cor.controller.FrontController.doProcess(FrontController.java:85)
    at com.nexcom.cor.controller.FrontController.doGet(FrontController.java:59)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:719)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:376)
    at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:870)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:451)
    at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:218)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
    at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
    at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:260)
    at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
    at java.lang.Thread.run(Thread.java:534)
    06/08/01 10:35:18 after try
    It does not goto catch block and not printing message from System.out.

    You can map error codes to a specific jsp in your web.xml file, and add a parameter to the jsp that will display the message you intend to display back to the user.
    Example:
    <error-page>
    <error-code>404</error-code>
    <location>/index.html</location>
    </error-page>
    You can also trap specific exceptions by doing the following:
    <error-page>
    <exception-type> java.lang.Exception </exception-type>
    <location>/ErrorPage.jsp</location>
    </error-page>

  • Question on exception catching

    Runtime exceptions are not subject to the Catch or Specify Requirement
    I came across this line in the Java tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/catchOrDeclare.html
    What did it mean?

    I understand some of what you write but I don't see
    how a compiler does not detect it. Sorry if I am
    sounding dumb. I never programmed before.Okay, more detailed explanation (which means I am in a good mood otherwise I don't like writing so much):
    Consider the following code.
    String s = null;
    // some code in between
    System.out.println(s.substring(0,1));What do you think will happen to this code? It will generate a NullPointerException when substring() is called on the String s unless something else is assigned to the s in between. Now this is something which can occur only when you execute your code.
    What I mean is, is there any way for the compiler to detect whether the value of the String variable s has changed? The answer is a plain no. It is not the job of the compiler to know that. So subsequently, a compiler cannot dictate to the programmer that a possible NullPointerException (NPE) needs to be handled because there is no way a compiler could be sure about a NPE in any case (unless it is too smart). There could be several other such exceptions which could occur. So that becomes an unchecked exception which is not checked by the compiler.
    Now coming to checked exception. If you are calling a method which already throws an exception as a known behaviour, the compiler is already aware. For example, a file read operation (I'm being lazy in typing code now) would throw an IOException which is defined as a part of the method signature. This makes the compiler aware of the possibility of getting an IOException. SO it checks to see if the programmer has taken care of the exception to make the code more fool-proof. This comes to be known as a checked exception.
    Does this make something clear? I hope so.

  • Exception catching in event processing thread

    Hello!
    How to catch exceptions occurring in event processing thread during repaints, mouse & keyboard event processing etc.? All uncatched exceptions displayed in screen but I need to write them in logfile.
    Anton

    Yes - push your own event processor on to the AWT event queue. See my replies at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=484167
    and
    http://forum.java.sun.com/thread.jsp?forum=57&thread=163020
    Although for two completely different purposes, this technique will also allow you to put your own try/catch around super.dispatchEvent()
    Hope that helps
    Tom

  • How to catch up Exception message?

    i have a question while using try{ ... }catch{ ... } clauses. for when update, delete, databse, there might be error occurred. all to often i do not deal with the message, only if to check log when serious problem i have to find it out; but i hope to learn how if i am able to display message of my own while erro occurrs. for instance, when falling into SQLException, originaly i might just utilize
    }catch(SQLException e){
    e.printStackTrace();
    is it possible for me to catch up message inside the printStackTrace that may happen while errors appearing? (or only down to catch{} clause be the last deadline that i am able to use? because i hope i am able to capture error code like ora-1234 and tranlate it into messages that user, who doesn't know too much about pc, can understand easily while reporting bug; and not just saying "we have problem here!")
    that is, if 'A' situation popping out, i hope to direct it to error page with special message shown. so does the same error page with different message specified while 'B' situation found out!
    any suggestions would be appreciated~
    thanks in advice,

    printStackTrace isn't obligatory. It's basically what you do with an exception when you don't have anything more specific to do with it.
    You can certainly catch a specific exception at any level, including inside another try {} block.
    Even having caught an exception you can decide that you don't want to handle it at this point in the code, and throw it again.
    You might do:
    try {
         try {
           ... statment which migh cause a particular database exception
            } catch(SQLException e) {
            if(e.getMessage().startsWith("ORA-1232")) {
              .. do somthing usefull
             } else
            throw e;   // the particular SQL exception was unexpected so go on and crash
       catch(Exception e) {
         e.printStackTrace();   // unexpected program failure

  • Write and read txt files and catch the exceptions

    hey everyone, im in a bit of a bind. im trying to set up this try catch statement. here is what i have for code so far.
    import java.util.Scanner;
    import java.io.*;
    public class Warning
        //   Reads student data (name, semester hours, quality points) from a
        //   text file, computes the GPA, then writes data to another file
        //   if the student is placed on academic warning.
        public static void main (String[] args)
         int creditHrs;         // number of semester hours earned
         double qualityPts;     // number of quality points earned
         double gpa;            // grade point (quality point) average
         String line, name, inputName = "students.dat";
         String outputName = "warning.dat";
         try
              Scanner FileScan1 = new Scanner (new File("students.dat"));
              // Set up scanner to input file
              // Set up the output file stream
              // Print a header to the output file
              outFile.println ();
              outFile.println ("Students on Academic Warning");
              outFile.println ();
              // Process the input file, one token at a time
              while (FileScan1.hasNext())//there is another line...
                  {               // Get the credit hours and quality points and
                   // determine if the student is on warning. If so,
                   // write the student data to the output file.
              // Close output file
         catch (FileNotFoundException exception)
              System.out.println ("The file " + inputName + " was not found.");
         catch (IOException exception)
              System.out.println (exception);
         catch (NumberFormatException e)
              System.out.println ("Format error in input file: " + e);
    }I am pretty sure the layout is good to go, but first and foremost that try statement is hanging me up. Could someone give me some suggestions about how i should set this up.
    i want to read in this students.dat file, then output another file called warning.dat.
    Thanks i really appreicate the help.

    no, i was really hoping to just see if the way it is
    set up it will be doable, that way i wouldn't be
    working on code that was impossiable to sort through
    properlyFair enough.
    One thing I'd suggest is that if you're really basically only going to be printing the exceptions, and since that is the top-level method (main) --
    I'd instead just add some "throws" clauses to main, get rid of the try/catch stuff, and just let the VM handle the exceptions for you. It will print them, just like you're doing, except that it will also print the stack traces, which you are not doing.
    If you're going to handle exceptions, it's better to actually do something about them rather than just print them - otherwise you might just as well let the runtime do that for you.

  • Help Me, How to catch exception thrown from ejbStore

    Hi,
    I am working on application running on Iplanet Application Server 4.0. Problem is the application exception thrown from the ejbStore don't reach the calling servlet, calling servlet receive TransactionRollback exception which is system exception. But there is no sign of my application exception thrown from ejbStore. Can anybody tell me how I can get my ApplicationException thrown from ejbStore in my calling servlet.
    I am calling entity beans set method in servlet and in entity bean ejbStore method I am throwing Application exception.
    in entity bean
    public void ejbStore() throws MyException
    if(true) throw new MyException();
    in servlet
    try {
    MyEntityHome home = .......
    MyEntityRemote remote = home.findBy.....
    remote.setMyValue(MyValue value); //Transaction required Container managed
    }catch(MyException e) {
    e.printStackTrace(); // Not cahcing My Exception
    }catch(Exception e) {
    e.printStackTrace(); //catching TransactionRolledBackException
    Thanks
    Shakti

    Hi Ravi
                                    Try this
                                                try
                    Object retMsgs = output.get(bapiretrunmsgobject);
                      if(result != null )
    IrecordSet rmsg = (IrecordSet) result
                   catch(Exception ex)
                        printException(ex, "Error getting function result");
    Lemme know for any further questions.
    Regards
    Praveen

  • Multiple catch for try -Exception Already caught Running smoothly..

    take this code for example...
    This one runs smoothly..
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
    }However if i change the order it would give me a compile time error which in my sun sl-275 book is written it should run fine.
    "If the Exception Catch clause is put first, then it would handle all exceptions, and the MyException or MyOtherException catch clauses would never be invoked."
    which i think is wrong because the code never gets compiled...
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(Exception e)
                   System.out.println(e);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
         }please discuss.

    DogsAreBarking wrote:
    take this code for example...
    This one runs smoothly..
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
    }However if i change the order it would give me a compile time error Correct. Each exception can be caught only once, Catching an exception implicitly catches every subclass exception of the one caught.
    In the first example, the code is fine, because your first catch block will catch only ArrayIndexOutOfBoundsException, and the second catch block will catch anything that was not caught previously--in other words, everything other than ArrayIndexOutOfBoundsException (and any child classes it may have).
    In the second example, the first catch block handles Exception and all of its subclasses, so catching ArrayIndexOutOfBoundsException is wrong.

  • Catching or Methods Throwing Exceptions

    Hi,
    I'm just wondering whats the difference between catching an exception and a method throwing an exception?
    I'm a bit confused on their purpose dealing with exceptions.
    catching an exception
    void p1()
              try{
                   p2();
              }catch(IOException ex){
         }method throwing an exception
    void p1() throws IOException
              p2();
         }

    one more stuff i need to add is that:
    When we declare a particular code within a try catch
    statement it means that that particular code is very
    much prone to an exception , i mean the programeer
    knows that code will throw a exception and hence we
    mention in try catch block.
    But in other case when we suffixed that particular
    method with throws clause it means the programmer is
    not sure ,that code might throw an exception,hence we
    put in throws clause.Not quite, the programmer always knows if a checked exception is being thrown, since the compiler requires it to be caught or having a throws clause. Unchecked (runtime) exceptions don't require a throws clause and the programmer must/can catch it if he wants to.

  • How to deal exception using try{}catch{}

    I don't know which is a good way from catch a exception and throw a exception,
    I means that how to use exception in java,catch ? throw?

    Presumably you are not asking the same thing as here...
    http://forum.java.sun.com/thread.jsp?thread=461313&forum=9&message=2114037
    You catch an exception with code that looks like the following...
        try
          String s = null;
          int i = s.length();  // This throws an exception
        catch(NullPointerException e)
          // Do something
    You throw an exception with the following...
        if (<some condition>)
           throw new Exception("Something bad happened");

  • Cant catch Exception

    Hi,
    Can anybody tell me why following program doesn't catch exception because of dereferencing a null pointer. Is there anything extra I have to do achieve it.
    #include <stdexcept>
    #include <exception>
    int main ()
    try
         int *ptr ;
         ptr = NULL;
         printf("%d" , *ptr);
    catch ( ... )
         printf("Exception catched\n");
    Thanks,

    This program is not throwing an exception. There is difference between UNIX signals (like NULL deref) and C++ exceptions.

  • Invalid Class Exception problem

    Hi whenever i try to run this method from a different class to the one it is declared in it throws invalid class exception, (in its error it says the class this method is written in is the problem) yet when i run it from its own class in a temporary main it works fine, perhaps someone can see the problem in the method code. All its doing is reading from a few different txt files, deserializing the objects and putting them into arraylists for future access.
    public void readCourseData()
              CourseArrayLengths cal;
              try
                   FileInputStream fis = new FileInputStream("arraylengths.txt");
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   cal = ((CourseArrayLengths) ois.readObject());     
                   ois.close();
                   FileInputStream fis1 = new FileInputStream("units.txt");
                   ObjectInputStream ois1 = new ObjectInputStream(fis1);
                   for(int i=0;i<cal.getUnitArrayLength();i++)
                        units.add((Unit) ois1.readObject());
                   ois1.close();
                   FileInputStream fis2 = new FileInputStream("sections.txt");
                   ObjectInputStream ois2 = new ObjectInputStream(fis2);
                   for(int i=0;i<cal.getSectionArrayLength();i++)
                        sections.add((Section) ois2.readObject());
                   ois2.close();
                   FileInputStream fis3 = new FileInputStream("files.txt");
                   ObjectInputStream ois3 = new ObjectInputStream(fis3);
                   for(int i=0;i<cal.getFileArrayLength();i++)
                        files.add((Filetype) ois3.readObject());
                   ois3.close();
              catch(FileNotFoundException exception)
              System.out.println("The File was not found");
              catch(IOException exception)
              System.out.println(exception);
              catch(ClassNotFoundException exception)
              System.out.println(exception);
         }

    import java.util.ArrayList;
    import java.io.*;
    import javax.swing.*;
    public class Unit implements Serializable
    ArrayList units = new ArrayList();
    ArrayList sections = new ArrayList();
    ArrayList files = new ArrayList();
    String unitName;
    int sStart=0,sEnd=0,sIndex=0,fIndex=0,subIndex=0;
         public Unit(String unitNamec,int sStartc,int sEndc)
              unitName = unitNamec;
              sStart = sStartc;
              sEnd = sEndc;
         public Unit()
         public String getUnitName()
              return unitName;
         public Unit getUnit(int i)
              return (Unit)units.get(i);
         public Section getSection(int i)
              return (Section)sections.get(i);
         public ArrayList getUnitArray()
              return units;
         public int getSectionStart()
              return sStart;
         public int getSectionEnd()
              return sEnd;
         public void setSectionStart(int i)
              sStart = i;
         public void setSectionEnd(int i)
              sEnd = i;
         public void addUnit(String uName)
              units.add(new Unit(uName,sections.size(),sIndex));
              sIndex++;
         public void addSection(String sName,Unit u)
              //problem lies with files.size()
              sections.add(new Section(sName,files.size(),files.size()));
              u.setSectionEnd(u.getSectionEnd()+1);
              //fIndex++;
         public void addFile(String fName,File fPath,Section s)
              files.add(new Filetype(fName,fPath));
              s.setFileEnd(s.getFileEnd()+1);
         public void display(Unit u)
              System.out.println(u.getUnitName());
              for(int i=u.getSectionStart();i<u.getSectionEnd();i++)
                   System.out.println(((Section)sections.get(i)).getSectName());
                   for(int j=((Section)(sections.get(i))).getFileStart();j<((Section)(sections.get(i))).getFileEnd();j++)
                        System.out.println(((Filetype)files.get(j)).getFileName());
         public void writeCourseData()
         //writes 3 arrays to 3 different files
    try
    FileOutputStream fos = new FileOutputStream("units.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<units.size();i++)
         oos.writeObject((Unit)units.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("sections.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<sections.size();i++)
         oos.writeObject((Section)sections.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("files.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<files.size();i++)
         oos.writeObject((Filetype)files.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("arraylengths.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         oos.writeObject(new CourseArrayLengths(units.size(),sections.size(),files.size()));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
         public void readCourseData()
              CourseArrayLengths cal;
              try
                   FileInputStream fis = new FileInputStream("arraylengths.txt");
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   cal = ((CourseArrayLengths) ois.readObject());     
                   ois.close();
                   FileInputStream fis1 = new FileInputStream("units.txt");
                   ObjectInputStream ois1 = new ObjectInputStream(fis1);
                   for(int i=0;i<cal.getUnitArrayLength();i++)
                        units.add((Unit) ois1.readObject());
                   ois1.close();
                   FileInputStream fis2 = new FileInputStream("sections.txt");
                   ObjectInputStream ois2 = new ObjectInputStream(fis2);
                   for(int i=0;i<cal.getSectionArrayLength();i++)
                        sections.add((Section) ois2.readObject());
                   ois2.close();
                   FileInputStream fis3 = new FileInputStream("files.txt");
                   ObjectInputStream ois3 = new ObjectInputStream(fis3);
                   for(int i=0;i<cal.getFileArrayLength();i++)
                        files.add((Filetype) ois3.readObject());
                   ois3.close();
              catch(FileNotFoundException exception)
              System.out.println("The File was not found");
              catch(IOException exception)
              System.out.println(exception);
              catch(ClassNotFoundException exception)
              System.out.println(exception);
         /*public static void main(String args[])
              Unit u1 = new Unit();
              u1.addUnit("Cmps2a22");
              u1.addSection("Section1",u1.getUnit(0));
              //u1.addSubSection("Subsect1",u1.getSection(0));
              u1.addFile("File1",null,u1.getSection(0));
              u1.addFile("File2",null,u1.getSection(0));
              u1.addSection("Section2",u1.getUnit(0));
              u1.addFile("NF",null,u1.getSection(1));
              u1.addFile("NF2",null,u1.getSection(1));
              u1.addFile("NF3",null,u1.getSection(1));
              u1.addSection("Section3",u1.getUnit(0));
              u1.addFile("NF",null,u1.getSection(2));
              u1.addFile("NF2",null,u1.getSection(2));
              u1.addFile("NF4",null,u1.getSection(2));
              u1.display(u1.getUnit(0));
              u1.writeCourseData();
              u1.readCourseData();
              u1.display(u1.getUnit(0));
    import java.util.ArrayList;
    import java.io.*;
    public class Section implements Serializable
    private String sectName,subSectName;
    private int fpStart=0,fpEnd=0,subSectStart=0,subSectEnd=0;
    private Section s;
    private boolean sub;
         public Section(String sectNamec,int fpStartc,int fpEndc,int subSectStartc,int subSectEndc,Section sc,boolean subc)
              sectName = sectNamec;
              fpStart = fpStartc;
              fpEnd = fpEndc;
              subSectStart = subSectStartc;
              subSectEnd = subSectEndc;
              s = sc;
              sub = subc;
         public Section(String sectNamec,int fpStartc,int fpEndc)
              sectName = sectNamec;
              fpStart = fpStartc;
              fpEnd = fpEndc;
         public Section getParent()
              return s;
         public boolean isSub()
              return sub;
         public String getSubName()
              return subSectName;
         public int getSubStart()
              return subSectStart;
         public int getSubEnd()
              return subSectEnd;
         public void setSubStart(int i)
              subSectStart = i;
         public void setSubEnd(int i)
              subSectEnd = i;
         public int getFileStart()
              return fpStart;
         public int getFileEnd()
              return fpEnd;
         public String getSectName()
              return sectName;
         public void setFileStart(int i)
              fpStart = i;
         public void setFileEnd(int i)
              fpEnd = i;
         public void addSection(String sectName)
         /*public static void main(String args[])
    import java.io.*;
    public class Filetype implements Serializable
         private String name;
         private File filepath;
         public Filetype(String namec, File filepathc)
              name = namec;
              filepath = filepathc;
         public String getFileName()
              return name;
         public File getFilepath()
              return filepath;
    import java.io.*;
    public class CourseArrayLengths implements Serializable
    private int ul,sl,fl;
         public CourseArrayLengths(int ulc,int slc,int flc)
              ul = ulc;
              sl = slc;
              fl = flc;
         public int getUnitArrayLength()
              return ul;
         public int getSectionArrayLength()
              return sl;
         public int getFileArrayLength()
              return fl;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.io.*;
    public class OrganiserGui implements ActionListener
    int width,height;
    JFrame frame;
         public OrganiserGui()
              width = 600;
              height = 500;
         public void runGui()
              //Frame sizes and location
              frame = new JFrame("StudentOrganiser V1.0");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setLocation(60,60);
              JMenuBar menuBar = new JMenuBar();
              //File menu
              JMenu fileMenu = new JMenu("File");
              menuBar.add(fileMenu);
              fileMenu.addSeparator();
              JMenu addSubMenu = new JMenu("Add");
              fileMenu.add(addSubMenu);
              JMenuItem cwk = new JMenuItem("Coursework assignment");
              addSubMenu.add(cwk);
              JMenuItem lecture = new JMenuItem("Lecture");
              lecture.addActionListener(this);
              addSubMenu.add(lecture);
              JMenuItem seminar = new JMenuItem("Seminar sheet");
              addSubMenu.add(seminar);
              //Calendar menu
              JMenu calendarMenu = new JMenu("Calendar");
              menuBar.add(calendarMenu);
              calendarMenu.addSeparator();
              JMenu calendarSubMenu = new JMenu("Edit Calendar");
              calendarMenu.add(calendarSubMenu);
              JMenuItem eventa = new JMenuItem("Add/Remove Event");
              eventa.addActionListener(this);
              calendarSubMenu.add(eventa);
              JMenuItem calClear = new JMenuItem("Clear Calendar");
              calClear.addActionListener(this);
              calendarSubMenu.add(calClear);
              JMenu calendarSubMenuView = new JMenu("View");
              calendarMenu.add(calendarSubMenuView);
              JMenuItem year = new JMenuItem("By Year");
              year.addActionListener(this);
              calendarSubMenuView.add(year);
              JMenuItem month = new JMenuItem("By Month");
              month.addActionListener(this);          
              calendarSubMenuView.add(month);
              JMenuItem week = new JMenuItem("By Week");
              week.addActionListener(this);
              calendarSubMenuView.add(week);
              //Timetable menu
              JMenu timetableMenu = new JMenu("Timetable");
              menuBar.add(timetableMenu);
              timetableMenu.addSeparator();
              JMenu stimetableSubMenu = new JMenu("Social Timetable");
              timetableMenu.add(stimetableSubMenu);
              JMenu ltimetableSubMenu = new JMenu("Lecture Timetable");
              timetableMenu.add(ltimetableSubMenu);
              frame.setJMenuBar(menuBar);
    frame.setVisible(true);
         public void actionPerformed(ActionEvent e)
              JMenuItem source = (JMenuItem)(e.getSource());
              System.out.println(source.getText());     
              Calendar c = new Calendar();
              if(source.getText().equalsIgnoreCase("By Year"))
                   System.out.println("INSIDE");
                   c.buildArray();
                   c.calendarByYear(Calendar.calendarArray);     
              if(source.getText().equalsIgnoreCase("Add/Remove Event"))
                   c.eventInput();
              if(source.getText().equalsIgnoreCase("clear calendar"))
                   c.buildYear();
                   c.writeEvent(Calendar.calendarArray);
                   c.buildArray();
              if(source.getText().equalsIgnoreCase("lecture"))
                   System.out.println("Nearly working");
                   //JFileChooser jf = new JFileChooser();
                   //jf.showOpenDialog(frame);
                   FileManager fm = new FileManager();
                   //choose unit to add file to
                   JOptionPane unitOption = new JOptionPane();
                   Unit u = new Unit();
                   u.readCourseData();
                   //u.display(u.getUnit(0));
                   System.out.println((u.getUnit(0)).getUnitName());
                   String[] unitNames = new String[u.getUnitArray().size()];
                   for(int i=0;i<unitNames.length;i++)
                        //unitNames[i] = (((Unit)u.getUnitArray().get(i)).getUnitName());
                        //System.out.println(unitNames);
                        System.out.println((u.getUnit(i)).getUnitName());
                   //unitOption.showInputDialog("Select Unit to add lecture to",unitNames);
                   //needs to select where to store it
                   //fm.openFile(jf.getSelectedFile());
         public static void main(String args[])
              OrganiserGui gui = new OrganiserGui();
              gui.runGui();
    java.io.invalidclassexception: Unit; local class incompatible: stream classdesc serialversionUID = 3355176005651395533, local class serialversionUID = 307309993874795880

  • Test exact exception messages in java SE with locale for program handling

    My problem is test the exact exceptions returned by JAVA Standard Engine for program handling.
    I work in systems usually set to "Italian Locale" and the result is different in different platforms.
    When I work in MSWindows with Java almost messages are in English but not all, for example IOException "Cannot assign requested address" in the Italian Locale is "Indirizzo richiesto non valido nel proprio contesto" but other messages like "Socket Closed" remain "Socket Closed".
    Catch the exact exception through description is not a good idea but I don't found other way for Java SE native exceptions!
    In Solaris I try to set English LANG environment in the user context and it works.
    In MS Windows I try to set the definition in start java with:
    *"java -Duser.language=en -Duser.region=US"*
    and in the code I try to add the statement:
    Locale.setDefault(Locale.US);
    but without results.
    Is there anybody that has the same problem?
    Is there a better way to catch the exact type of Java SE exceptions ?
    My test Environments:_
    Solaris 10 jdk 1.6.0.02
    MS Windows 2000 jdk 1.6.0.02
    MS Windows XP jdk1.6.0.02 and 1.5.0.12
    Fragment program example for additional explanation:_
    try {
    } catch (IOException ex) {
    if (ex.getMessage().equals("Socket Closed"))
    System.out.println("Ok socket closed exception catched");
    if (ex.getMessage().equals("Cannot assign requested address"))
    System.out.println("Ok assign requested address exception catched");
    }

    My problem is test the exact exceptions returned by JAVA Standard Engine for program handling.
    I work in systems usually set to "Italian Locale" and the result is different in different platforms.
    When I work in MSWindows with Java almost messages are in English but not all, for example IOException "Cannot assign requested address" in the Italian Locale is "Indirizzo richiesto non valido nel proprio contesto" but other messages like "Socket Closed" remain "Socket Closed".
    Catch the exact exception through description is not a good idea but I don't found other way for Java SE native exceptions!
    In Solaris I try to set English LANG environment in the user context and it works.
    In MS Windows I try to set the definition in start java with:
    *"java -Duser.language=en -Duser.region=US"*
    and in the code I try to add the statement:
    Locale.setDefault(Locale.US);
    but without results.
    Is there anybody that has the same problem?
    Is there a better way to catch the exact type of Java SE exceptions ?
    My test Environments:_
    Solaris 10 jdk 1.6.0.02
    MS Windows 2000 jdk 1.6.0.02
    MS Windows XP jdk1.6.0.02 and 1.5.0.12
    Fragment program example for additional explanation:_
    try {
    } catch (IOException ex) {
    if (ex.getMessage().equals("Socket Closed"))
    System.out.println("Ok socket closed exception catched");
    if (ex.getMessage().equals("Cannot assign requested address"))
    System.out.println("Ok assign requested address exception catched");
    }

Maybe you are looking for

  • Settings and configuration for APO SNP?

    Hi, we want to use SNP in the future. Which configuration must be done in the APO customizing? Which data must be transferred from R/3 to APO? Does anybody has a kind of check list for the necessary settings? Thanks, Michael

  • Camera not working for my omni10

    i have problem with camera. When i click icon it shows back sreen only.

  • Re-installing elements 13 after hard drive meltdown

    old laptop fried; can't re-install Elements 13 on new laptop; error notice says: This serial number is already in use by the maximum number of computers. You must deactivate another compouter... Impossible to access old hard drive

  • Image Quality issue with script

    So I recently wrote a simple script to output an image at a bunch of different resolutions. However, I am running into an image quality issue that I don't run into when I do the same thing manually. Here is an example image showcasing the image: http

  • Switching to develop, all phot's turn green

    Hello, I have had to fit a new hard drive to my desktop pc, the pc is running windows 7 premium, I have reinstalled as per my old hard drive, I installed Lightroom 4 everything went fine, I imported some RAW photo's from a disc,again ok the photo's w