Which type of exceptions must be caught?

Hello,
could somebody give me a clue why some exceptions must be caught while others must not?
i.e. java.lang.Class.getMethod() throws NoSuchMethodException...
must be caught while
java.lang.Integer.parseInt(String s) throws NumberFormatException
does go by unnoticed by the compiler.
Thanks in advance,
Stephan

Classes that extend Error and RuntimeException do not need to be caught. (Technically, you do not have to declare them in the throws clause or catch them in the method, but you probably do want to handle these errors somewhere, unless you are working in a J2EE container.)
All other subclasses of Throwable must be declared in a throws clause or caught.
Throwable (extends Object) - checked exception
Exception (extends Throwable) - checked exception
Error (extends Throwable) - un-checked exception
RuntimeException (extends Exception) - un-checked exception
- Saish

Similar Messages

  • Unreported exception java.lang.Exception; must be caught or declared

    I've got a piece of code that's causing an error during compilation.
    W:\Java\Covenant\src\covenant\Login.java:174: unreported exception java.lang.Exception; must be caught or declared to be thrownThe line of code it is refering to is:
    new Overview().setVisible(true);And it is part of a try/catch statement:
        private void logincheck(java.awt.event.ActionEvent evt) {                           
            try {
                char[] PasswordInput = Password.getPassword();
                String PasswordRaw = new String(PasswordInput);
                String Passwordmd5 = md5(PasswordRaw);
                String UsernameInput = Username.getText();
                URL theUrl = new URL("http://www.phoenixrising.at/iris/validate.php?login=1&u=" + UsernameInput + "&p=" + Passwordmd5 +"");
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        theUrl.openStream()));
                String inputLine = in.readLine();
                if (inputLine.equals("valid")) {
                    new Overview().setVisible(true);
                    this.setVisible(false);
                    System.out.println( "You have entered the correct password" );
                } else {
                    System.out.println(theUrl);
                in.close();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
        }      Can anyone see what might be causing this error?

    Can anyone see what might be causing this error? That line of code declares that it throws exception java.lang.Exception, so you must either catch it ("must be caught" - like you do the more specific Exceptions) or declare your logincheck method to throw it ("or declared to be thrown").

  • Exception must be caught or declared to be thrown?

    got two errors when compling:
    TryCalendar.java [20:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
    int day = in.readInt();
    ^
    TryCalendar.java [21:1] unreported exception InvalidUserInputException; must be caught or declared to be thrown
    int month = in.readInt();
    Is there anyone could kindly tell me how to solve? Thank you very much! The short source code as following:
    import java.util.GregorianCalendar;
    import java.text.DateFormatSymbols;
    public class TryCalendar {
    public static void main(String[] args) {
    FormattedInput in = new FormattedInput();
    // Get the date of birth from the keyboard
    System.out.println("Enter your birth date as dd mm yyyy: ");
    int day = in.readInt();
    int month = in.readInt();
    int year = in.readInt();
    // Create birht date calendar - month is 0 to 11
    GregorianCalendar birthdate = new GregorianCalendar(year, month-1, day);
    GregorianCalendar today = new GregorianCalendar(); // Today's date
    // Create this year's birthday
    GregorianCalendar birthday = new GregorianCalendar(
    today.get(today.YEAR),
    birthdate.get(birthdate.MONTH),
    birthdate.get(birthdate.DATE));
    int age = today.get(today.YEAR) - birthdate.get(birthdate.YEAR);
    String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names
    System.out.println("You were born on a " + weekdays[birthdate.get(birthdate.DAY_OF_WEEK)]);
    System.out.println("This year you " + (birthday.after(today) ?"will be " : "are " ) + age + " years old.");
    System.out.println("This year your birthday " + (today.before(birthday)? "will be": "was") + "on a " + weekdays[birthday.get(birthday.DAY_OF_WEEK)]);
    }

    The compiler error has to do with "Exceptions"
    "Exceptions" are things that might go wrong while the program is running. In this case, the user might type "ABC" when the program is trying to read a number using readInt. If the user does this, then that line of code will "throw" an "InvalidUserInputException".
    Your code must "handle" the exception. There are two ways to do this.
    Note that your code is part of a method, namely, the main method
    public static void main(String args[])
      int day = in.readInt(); // Exception might be thrown here
    }   // end of main methodThe first way to deal with the Exception is to decide that main will throw it. Already, readInt throws the Exception to main, now we will make main in turn throw the exception back to whatever called it.
    This can be done as follows. Note the change to the declaration of main.
    public static void main(String args[]) throws InvalidUserInputException
      int day = in.readInt(); // Exception might be thrown here
    }   // end of main methodThen your code should compile and run. This method is not recommended - if the user types in ABC, the program will crash with a cryptic error message.
    It is much better, if readInt throws the Exception, to have your code catch it. To do this, the code that might throw the exception must be contained in a try block, which must be followed by a catch block.
    public static void main(String args[])
      try {
        int day = in.readInt(); // Exception might be thrown here
      } // end of try block
      catch (InvalidUserInputException iue) { 
        ... // code to handle the exception
    }   // end of main methodWhat this means is that java will "try" to perform the code in the try block, and if the user types ABC instead of a number, the InvalidUserInputException thrown by int day=in.readInt() will be "caught", and the code in the catch block will run. The code in the catch block can be anything you like. The most sensible thing to do would be to print some error message informing the user that they typed something wrong. Maybe something like:
       boolean done = false;
       int day,month,year;
       do {
          try {
             System.out.println("Enter your birth date as dd mm yyyy: ");
             day = in.readInt();      // line (1)
             month = in.readInt();    // line (2)
             year = in.readInt();     // line (3)
             done = true;             // line (4)
          catch (InvalidUserInputException iuie) {
             System.out.println("Are you trying to confuse me? I'm only a poor harmless computer! ");       // line (5)
             System.out.println("dd mm and yyyy must be numbers!");
        } while (!done);If an Exception is thrown on lines (1), (2) or (3), then line (4) will not be reached - instead, the program will run from line (5). Since done is still false, the program will loop back to ask for the birthdate again.
    If no exception is thrown, line (4) ensures that the loop will finish, and the catch block is skipped altogether.
    Hope that makes things clearer :-)
    Yours, Mike H...

  • Unreported exception java.rmi.RemoteException; must be caught or declared t

    I am receiving an:
    unreported exception java.rmi.RemoteException; must be caught or declared to be thrown
    error when I attempt to compile the Client.java file.
    The Client.java file implements the ATMListener.java interface.
    As you will see below, I've stripped them down by taking out all of the code, yet I still receive this error.
    Any ideas...
    ATMListener.java
    import java.rmi.*;
    import java.rmi.server.UnicastRemoteObject;
    * @author Eddie Brodie
    * @version %I%, %G%
    public interface ATMListener extends java.rmi.Remote
    Client.java
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.rmi.UnknownHostException;
    public class Client extends java.rmi.server.UnicastRemoteObject implements ATMListener

    Well first off unless I am missing something in the API java.rmi.Remote is an interface not a class so implements not inherits, but I do not really know these classes so I cannot be sure I am not missing something.
    As for the unreported exception. What could be causing something like this would be an exception thrown by the constructor of the parent class. Even if you have no constructor written for your class it still has a default constructor which will by default call the super constrcutpor meaning an exception could be thrown from the super constrcutor down to your default constructor where you would not know what to do with it.

  • Unreported exception; java.sql.SQLException; must be caught or declared to

    Hi everyone,
    For my Java course assignment we need to make a small application that uses a MS Access database. But de code below gives me a "Unreported exception; java.sql.SQLException; must be caught or declared to be thrown at line xx" error.
    public class ConnectieBeheer
      private static Connection con;
      private static Statement stmt;
      private static ResultSet res;
      private static ResultSetMetaData md;
      private ConnectieBeheer(){}
      public static void openDB() {
        Driver driver = new JdbcOdbcDriver();
        Properties info = new Properties();
        String url = "jdbc:odbc:theater";
        con = driver.connect(url, info);       <--- Error here
        if (con != null)
          stmt =  con.createStatement();      <--- Error here
          DatabaseMetaData dma = con.getMetaData();      <--- Error here
      }So I tried this :
    public static void openDB() throws SQLException {Now I do not get an error.
    The OpenDB method is called from a different class like this :
      public static void test1(){
        ConnectieBeheer.openDB();
        System.out.println("DB opened");
      }But now it gives the same "Unreported exception; java.sql.SQLException; must be caught or declared to be thrown at line xx" error but now at the line ConnectieBeheer.openDB();
    Why is this? And what can I do to correct this?
    Thanks!
    Steven.

    you should read the sun tutoriel about exceptions handling ;
    there are two ways to handle an exception : either you redirects it (using "throws" statement, what you did for the openDB method), or you catch it using a try { ... } catch (Exception exc) {}
    if you want to get rid of the error what you can do is :
      public static void test1(){
        try {
            ConnectieBeheer.openDB();
        } catch (java.sql.SQLException sqle) {
            sqle.printStackTrace();
        System.out.println("DB opened");
      }

  • Must be caught or declared to be thrown ! Help !

    Dear Java People,
    I have only one error in my program in the TryVectorAndSort class
    "Unreported exception (InvalidUserInputException)
    Must be caught or declared to be thrown lines 41,49"
    >>    String firstName = in.readString().trim();
    >>     String lastName = in.readString().trim();
    so the error in the above 2 lines points to the readString() method
    which is below
      public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserInputException(" readString() failed. " + " Input data is not a string");
    below is the entire FormattedInput class
    Thank you in advance
    Norman
    import java.io.*;
    import java.util.*;
    public class FormattedInput
        // Method to read an int value
        public int readInt()
          for(int i = 0; i < 2; i++)
          if(readToken() == tokenizer.TT_NUMBER)
            return (int)tokenizer.nval;   // value is numeric so return as int
          else
            System.out.println("Incorrect input: " + tokenizer.sval +
               " Re-enter as integer");
            continue;         //retry the read operation
          }  //end of if statement
          System.out.println("Five failures reading an int value" + " - program terminated");
          System.exit(1);  // end the program
          return 0;
        } //end of method
         public double readDouble() throws InvalidUserInputException
           if(readToken() != tokenizer.TT_NUMBER)
              throw new InvalidUserInputException(" readDouble() failed. " + " Input data not numeric");
           return tokenizer.nval;
         public String readString() throws InvalidUserInputException
           if(readToken() == tokenizer.TT_WORD || ttype == '\"' ||  ttype == '\'')
            return tokenizer.sval;
           else
             throw new InvalidUserException(" readString() failed. " + " Input data is not a string");
           //helper method to read the next token
           private int readToken()
             try
               ttype = tokenizer.nextToken();
               return ttype;
             catch(IOException e)
               e.printStackTrace(System.err);
               System.exit(1);
              return 0;
           //object to tokenize input from the standard input stream
           private StreamTokenizer tokenizer = new StreamTokenizer(
                                                new BufferedReader(
                                                 new InputStreamReader(System.in)));
           private int ttype;                  //stores the token type code
    import java.io.*;
    import java.util.*;
    public class TryVectorAndSort
         public static void main(String[] args)
        Person aPerson;           // a Person object
        Crowd filmCast = new Crowd();
        //populate the crowd
        for( ; ;)
          aPerson = readPerson();
          if(aPerson == null)
            break;   // if null is obtained we break out of the for loop
          filmCast.add(aPerson);
        int count = filmCast.size();
        System.out.println("You added " + count + (count == 1 ? " person":  " people ") + "to the cast.\n");
        //Show who is in the cast using an iterator
         Iterator myIter = filmCast.iterator();
        //output all elements
        while(myIter.hasNext() )
          System.out.println(myIter.next());
        }//end of main
          //read a person from the keyboard
          static public Person readPerson()
         FormattedInput in = new FormattedInput();
            //read in the first name and remove blanks front and back
            System.out.println("\nEnter first name or ! to end:");
            String firstName = in.readString().trim(); //read and trim a string
            //check for a ! entered. If so we are done
            if(firstName.charAt(0) == '!')
              return null;
            //read the last name also trimming the blanks
            System.out.println("Enter last name:");
            String lastName = in.readString().trim();    // read and trim a string
            return new Person(firstName, lastName);
    //when I ran the program the output I received was:
    import java.io.StreamTokenizer;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class InvalidUserInputException extends Exception
       public InvalidUserInputException() { }
          public InvalidUserInputException(String message)
              super(message);
    public class Person implements Comparable
      public Person(String firstName, String lastName)
        this.firstName = firstName;
        this.lastName = lastName;
      public String toString()
        return firstName + "  " + lastName;
       //Compare Person objects
        public int compareTo(Object person)
           int result = lastName.compareTo(((Person)person).lastName);
           return result == 0 ? firstName.compareTo(((Person)person).firstName):result;
      private String firstName;
      private String lastName;
    import java.util.*;
    class Crowd
      public Crowd()
        //Create default Vector object to hold people
         people = new Vector();
      public Crowd(int numPersons)
        //create Vector object to hold  people with given capacity
         people = new Vector(numPersons);
        //add a person to the crowd
        public boolean add(Person someone)
          return people.add(someone);
         //get the person at the given index
          Person get(int index)
          return (Person)people.get(index);
         //get the numbers of persons in the crowd
          public int size()
            return people.size();
          //get  people store capacity
          public int capacity()
            return people.capacity();
          //get a listIterator for the crowd
          public Iterator iterator()
            return people.iterator();
            //A Vector implements the List interface (that has the static sort() method
            public void sort()
              Collections.sort(people);
          //Person store - only accessible through methods of this class
          private Vector people;
    }

    Dear Levi H,
    When I changed the catch block type to
    String lastName= "";
    try
    lastName = in.readString().trim(); //read and trim a string
    catch(InvalidUserInputException e)
    e.printStackTrace(System.err);
    I no longer have errors in the driver class but in the FormattedInput
    class there are new errors that say:
    "FormattedInput.java": Error #: 204 : illegal start of expression at line 49,68
    "FormattedInput.java": Error #: 206 : malformed expression at line 39,49
    Help !
    Norman

  • Error: java.sql.SQLException; must be caught or declared to be thrown.

    in a servlet, I have a class like:
    class mydb
    public static Connection conn;
    public static void init() throws SQLException
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection ("jdbc:oracle:oci8:@baby", "scott", "tiger");
    public static String getValue() throws SQLException
    String curValue="";
    // Create a Statement
    Statement stmt = conn.createStatement ();
    // Select the ENAME column from the EMP table
    ResultSet rset = stmt.executeQuery ("select ENAME from EMP");
    // Iterate through the result and print the employee names
    if (rset.next ())
    curValue = rset.getString (1);
    // Close the RseultSet
    rset.close();
    // Close the Statement
    stmt.close();
    return(curValue);
    public static void destroy() throws SQLException
    // Close the connection
    conn.close();
    but when it is called, errors "java.sql.SQLException; must be caught or declared to be thrown." encountered, how to solve this problem? please help.

    This is part of the Java language.
    If a method throws an exception, then
    it is telling you that the exception is
    something that you should be aware of.
    If you call a method which throws this exception, then the method must either catch this exception, or you may decide that this exception should be caught by the calling method.
    So, your choices are:
    1. Wrap the method call in a try{...} catch block
    -or-
    2. Change the (calling) method's signature to reflect the fact that this method can cause this exception to be thrown (add a 'throws SQLException' ) at end of signature.
    -John
    null

  • Unsupported response content type "text/html", must be: "tex

    Hi Gurus,
    I'm trying to access a WebService (http://200.68.11.21/WebServices/RecibeMsgSoapISP.wsdl), but I've been facing the following problem below. Could anybody help me?
    //****************************** MY CODE
    FileInputStream file = new FileInputStream("c:\\EXE\\deuda2.xml");
    byte[] bytes = new byte[file.available()];
    file.read(bytes);
    String xml = new String(bytes);
    System.out.println("Xml:\n" + xml);
    URL endPoint =
    new URL(
    "http://200.68.11.21/WebServices/RecibeMsgSoapISP.wsdl");
    Call call = new Call();
    SOAPTransport m_httpConnection =
    new org.apache.soap.transport.http.SOAPHTTPConnection();
    call.setSOAPTransport(m_httpConnection);
    call.setTargetObjectURI("urn:RecibeMsgSoapIsp");
    call.setMethodName("RecibeM2TGR");
    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
    //SOAPTransport st = new SOAPHTTPConnection();
    //call.setSOAPTransport(st);
    Vector params = new Vector();
    params.addElement(new Parameter("StrXml", String.class, xml, null));
    call.setParams(params);
    //call.setHeader();
    Response response = call.invoke(endPoint, "");
    Parameter result = response.getReturnValue();
    System.out.println("result:" + result);
    //****************************** MY EXCEPTION
    [SOAPException: faultCode=SOAP-ENV:Protocol; msg=Unsupported response content type "text/html", must be: "text/xml". Response was:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <html dir=ltr>
    <head>
    <style> a:link               {font:8pt/11pt verdana; color:FF0000} a:visited          {font:8pt/11pt verdana; color:#4e4e4e}
    </style>
    <META NAME="ROBOTS" CONTENT="NOINDEX">
    <title>No se puede mostrar la p&aacute;gina</title>
    <META HTTP-EQUIV="Content-Type" Content="text-html; charset=Windows-1252">
    </head>
    <script>
    function Homepage(){
    <!--
    // in real bits, urls get returned to our script like this:
    // res://shdocvw.dll/http_404.htm#http://www.DocURL.com/bar.htm
         //For testing use DocURL = "res://shdocvw.dll/http_404.htm#https://www.microsoft.com/bar.htm"
         DocURL=document.URL;
         //this is where the http or https will be, as found by searching for :// but skipping the res://
         protocolIndex=DocURL.indexOf("://",4);
         //this finds the ending slash for the domain server
         serverIndex=DocURL.indexOf("/",protocolIndex + 3);
         //for the href, we need a valid URL to the domain. We search for the # symbol to find the begining
         //of the true URL, and add 1 to skip it - this is the BeginURL value. We use serverIndex as the end marker.
         //urlresult=DocURL.substring(protocolIndex - 4,serverIndex);
         BeginURL=DocURL.indexOf("#",1) + 1;
         urlresult=DocURL.substring(BeginURL,serverIndex);
         //for display, we need to skip after http://, and go to the next slash
         displayresult=DocURL.substring(protocolIndex + 3 ,serverIndex);
         InsertElementAnchor(urlresult, displayresult);
    function HtmlEncode(text)
    return text.replace(/&/g, &apos;&amp&apos;).replace(/&apos;/g, &apos;&quot;&apos;).replace(/</g, &apos;&lt;&apos;).replace(/>/g, &apos;&gt;&apos;);
    function TagAttrib(name, value)
    return &apos; &apos;+name+&apos;="&apos;+HtmlEncode(value)+&apos;"&apos;;
    function PrintTag(tagName, needCloseTag, attrib, inner){
    document.write( &apos;<&apos; + tagName + attrib + &apos;>&apos; + HtmlEncode(inner) );
    if (needCloseTag) document.write( &apos;</&apos; + tagName +&apos;>&apos; );
    function URI(href)
    IEVer = window.navigator.appVersion;
    IEVer = IEVer.substr( IEVer.indexOf(&apos;MSIE&apos;) + 5, 3 );
    return (IEVer.charAt(1)==&apos;.&apos; && IEVer >= &apos;5.5&apos;) ?
    encodeURI(href) :
    escape(href).replace(/%3A/g, &apos;:&apos;).replace(/%3B/g, &apos;;&apos;);
    function InsertElementAnchor(href, text)
    PrintTag(&apos;A&apos;, true, TagAttrib(&apos;HREF&apos;, URI(href)), text);
    //-->
    </script>
    <body bgcolor="FFFFFF">
    <table width="410" cellpadding="3" cellspacing="5">
    <tr>
    <td align="left" valign="middle" width="360">
         <h1 style="COLOR:000000; FONT: 13pt/15pt verdana"><!--Problem-->No se puede mostrar la p&aacute;gina</h1>
    </td>
    </tr>
    <tr>
    <td width="400" colspan="2"> <font style="COLOR:000000; FONT: 8pt/11pt verdana">No se puede mostrar la p&aacute;gina que est&aacute; buscando porque la direcci&oacute;n de la p&aacute;gina es incorrecta.</font> </td>
    </tr>
    <tr>
    <td width="400" colspan="2"> <font style="COLOR:000000; FONT: 8pt/11pt verdana">
         <hr color="#C0C0C0" noshade>
    <p>Pruebe lo siguiente:</p>
         <ul>
    <li>Si escribi&oacute; la direcci&oacute;n de la p&aacute;gina en la barra de direcciones, compruebe que la ha escrito correctamente.<br>
    </li>
    <li>Abra la p&aacute;gina principal
    <script>
         <!--
         if (!((window.navigator.userAgent.indexOf("MSIE") > 0) && (window.navigator.appVersion.charAt(0) == "2")))
              Homepage();
         //-->
         </script>
         y busque v&iacute;nculos a la informaci&oacute;n que desee.</li>
    </ul>
    <h2 style="COLOR:000000; FONT: 8pt/11pt verdana">HTTP 405 &ndash; Resource not allowed<br> Servicios de Internet Information Server</h2>
         <hr color="#C0C0C0" noshade>
         <p>Informaci&oacute;n t&eacute;cnica (para personal de soporte)</p>
    <ul>
    <li>M&aacute;s informaci&oacute;n:<br> Soporte t&eacute;cnico de Microsoft
    </li>
    </ul>
    </font></td>
    </tr>
    </table>
    </body>
    </html>
         at org.apache.soap.rpc.Call.getEnvelopeString(Call.java:208)
         at org.apache.soap.rpc.Call.invoke(Call.java:255)
         at test.Test.main(Test.java:42)
    Best regards,
    George

    Is this statement that causes the exception? "Response response = call.invoke(endPoint, "");"
    If so you might be able to catch the SOAPException and interogate the response variable - surround the call with a try, catch block and within the catch you can get the MimeHeaders and check "Content-Type" If it's "text/html" then you know it not a SOAP message so don't use the SOAP api calls.
    It sounds like the web service is offline and the web server is trying to send you an HTML error page which of course is not a SOAP message and so a SOAPException is thrown.

  • Exception not always caught in Sun Studio 12

    Hi,
    We're using Sun Studio 12 (Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25) on a Solaris 10 SPARC machine. In our applications an exception thrown is sometimes not caught in the try/catch statement and the program continues at an outer catch statement (which usually leads to the program exiting). So far I've not been able to reduce the code down to a simple example and I don't yet know what conditions causes this behaviour.
    In general the code has a big try/catch statement in main. Somewhere deep in the code there is a second try/catch statement which protects against a piece of code which we know may throw an exception. This is usually a smart pointer being dereferenced. The act of dereferencing the smart pointer in turn causes an exception to be thrown which is caught internally in a third try/catch inside the dereference code. The exception is successfully caught and some clean up is done. Then the exception is re-thrown by either using a throw; statement or a new throw xmsg("...");. All our exceptions are always of type xmsg which simply takes a string argument.
    When the problem manifests itself the second try/catch is ignored and the re-thrown exception is instead caught in the outer catch statement in main which causes the program to log an error and exit.
    We have lots of code which is structured the same way and the same style of code works in many cases only to fail in some specific case. It's an elusive problem because the problem moves around and it also depends on how the program is compiled. It only seems to happen when compiled in debug mode. If I compile with -xO4 the problem seems to go away.
    The problem also goes away or moves to a different place if the code has changed somewhere between compiles, i.e. some other developer has modified some code, not necessarily in the same are where the problem originally happened.
    One thing we have is a function we call DoThrow (used to suppress a warning on an older compiler) defined like this:
    void DoThrow(const std::string& msg)
      throw xmsg(msg);
    }As an experiment I replaced the call to DoThrow with a straight throw xmsg(...) at a place where the first exception was thrown and the problem went away. I'm not sure if removing the call to DoThrow fixed the problem or if the minor restructuring of the code was enough to move the problem elsewhere.
    For production releases we still use WorkShop 6, update 2 which does not have any problems like this. We really would like to upgrade to Sun Studio 12 because it's a much better compiler over all. We can't upgrade until we feel confident we have a workaround.
    Does anyone have any thoughts on what might be wrong or any ideas on what I can do to narrow down the problem?
    Thanks,
    Krister

    Many thanks. You've given me a few areas to focus on and I'll bring my house in order.
    The only external C++ library we depend on is STLport 5.0.2 which we compile ourselves. It's currently compiled with 5.3 on Solaris 8 and I will recompile it with 5.9 on Solaris 10. All other external libraries are C libraries. Our own code is put in static libraries and linked statically. I've read that exceptions thrown in shared libraries can be problematic.
    Your comment about complex conditional expressions (a ? f() : g()) is interesting. We've been bitten before by compiler bugs affecting those types of expressions. Destructors called twice or destructors called for temporaries never created. We may still have some conditional expressions like that.
    The exception is of type xmsg, defined this way:
    class xmsg
      public:
        xmsg(const char* s) : _msg(s) {}
        xmsg(const std::string& s) : _msg(s) {}
        const std::string& why() const { return _msg; }
      private:
        const std::string _msg;
    };There are three catch blocks involved and all the try/catch statement look like this:
    try
    catch(const xmsg& msg)
    }Here is a stack trace from dbx at the point where the exception is thrown the first time.
      [1] __exdbg_notify_of_throw(0xffbf4ae8, 0xffbf4ad0, 0x959b292c, 0xffff0000, 0x0, 0xfc00), at 0xfb6549b4
      [2] _ex_debug_handshake1(0x0, 0x101cb84, 0x1, 0x14ffc, 0xfb66a67c, 0xfb66ad38), at 0xfb655728
      [3] _ex_throw_body(0xfb66af80, 0x80b2ac, 0xfb66a67c, 0x14d9c, 0x0, 0xfb66af80), at 0xfb655934
      [4] __Crun::ex_throw(0xfb66afd0, 0x1460bf8, 0x7ead20, 0x0, 0x16538, 0x1), at 0xfb6558bc
    =>[5] TransportSource<User>::Activate(this = 0x1624810, r = CLASS, _ARG3 = CLASS), line 39 in "TransportSource.H"
      [6] Source<User>::DoActivate(this = 0x162486c, r = CLASS, e = CLASS), line 272 in "Factory.H"
      [7] BaseFactory::Load(this = 0x16020a8, e = CLASS), line 2799 in "BaseFactory.C"
      [8] GPAuthorizationSource::Load(this = 0x15d2440), line 110 in "GPAuthorization.C"
      [9] ExchangeServer::ExchangeServer(this = 0xffbfa95c, argc = 8, argv = 0xffbfbaec), line 380 in "exchangeServer.C"
      [10] main(argc = 8, argv = 0xffbfbaec), line 1525 in "exchangeServer.C"Here is the code for the Activate function in stack frame 5. The exception thrown is the second one.
        virtual T& Activate(const Reference& r, Exemplar<T>&)
          _transport->In().Write(r);
          DemarshallStream out;
          _transport->Method(Process::Activate, out);
          if(!out.Data())
         throw xmsg("Failed to call Activate on server " + _transport->Name());
          if(!out.GetBool())
         throw xmsg("Server returned error: " + out.GetString());
          const ClassHandle& h = out.GetClassHandle(&_connection);
          // don't need to pass refresh flag here because a call to Activate
          // means the object is being loaded for the first time.
          BaseExemplar* x = _handle.GetFactory().Demarshall(h, out, false,
         &_connection, this);
          BaseTransportSource::DoActivate(out);
          if(!x)
         throw xmsg("Failed to activate ref: " + r.ExternalValue());
          return static_cast<T&>(*x->GetInstance());
        }The exception is caught (frame 7 in the stack trace above) and re-thrown in the below code, at the last throw statement.
    void BaseFactory::Load(BaseExemplar& e)
      SourceMap::iterator p = _sources.find(&e._key->Type());
      if(p == _sources.end())
        throw xmsg("Factory<" + _handle.Name() + ">::Load - no source for: "
          + e._key->ExternalValue());
      AutoPointer<BaseGuard> g(Guard());
      std::list<BaseSource*>::iterator i = p->second.begin();
      while(true)
        try
          (*i)->_currentExemplar = &e;
          BO& x = (*i)->DoActivate(*e._key, e);
          (*i)->_currentExemplar = 0;
          if(!e._instance)
         e._instance = &x;
         Activate(e, ActivatedOld, 0);
          return;
        catch(const xmsg& msg)
          (*i)->_currentExemplar = 0;
          ++i;
          if(i == p->second.end())
         throw;
    }There is a second try/catch one level up (stack frame 8, the call to GPAuthorizationSource::Load). Here's a snippet of that piece of code.
        try
          const Exemplar<User>& user = UserFactory::Instance().CreateExemplar(
         *new UserReference(authorizationTable._login.Value()));
          *user;
        catch(const xmsg& msg)
          Logger::Instance() << LogHeader << MsgClass(MsgClass::Error)
         << "Error PMAutorizationSource: " << msg.why() << EndMsg;
        // ...I put a break-point in the catch block in the above code but I never hit the break point and the exception is caught in an outer try/catch, an error is printed and the program exits.
      try
      catch(const xmsg& msg)
        std::cerr << "ERROR: " << msg.why() << std::endl;
      }I'm sorry I have not yet been able to produce a smaller example that can be compiled and tested in isolation. I know that's important in order to track down the problem. It seems like the smallest change in seemingly unrelated parts of the code makes the problem come or go.

  • Mailing attachments; java.io.IOException; must be caught or declared to be

    I seem to be having trouble setting up to attach a file and I'm getting the error message
    java.io.IOException; must be caught or declared to be
    //other related code
        String bookingFilename = "what ever filename";
    // create some properties and get the default Session
         Properties props = new Properties();
         props.put("mail.smtp.host", host);
         Session session = Session.getInstance(props, null);
         //session.setDebug(debug);
         try {
             // create a message
             MimeMessage msg = new MimeMessage(session);
             msg.setFrom(new InternetAddress(from));
             InternetAddress[] address = {new InternetAddress(to)};
             msg.setRecipients(Message.RecipientType.TO, address);
             msg.setSubject(subject);
             msg.setSentDate(new Date());
             // create and fill the first message part
             MimeBodyPart mbp1 = new MimeBodyPart();
             mbp1.setText(msgText1);
             // create and fill the second message part
             MimeBodyPart mbp2 = new MimeBodyPart();
                //PROBLEM LINE
                mbp2.setFilename(bookingFilename);
             // create the Multipart and its parts to it
             Multipart mp = new MimeMultipart();
             mp.addBodyPart(mbp1);
             mp.addBodyPart(mbp2);
             // add the Multipart to the message
             msg.setContent(mp);
             // send the message
             Transport.send(msg);
         } catch (MessagingException mex) {
             mex.printStackTrace();
             Exception ex = null;
             if ((ex = mex.getNextException()) != null) {
              ex.printStackTrace();the following is the problem code
    mbp2.setFilename(bookingFilename);am I putting the filename in the wrong format?
    I'm hoping to specify the exact filename using "if" statements so the current
    String bookingFilename = "what ever filename";is just a placeholder
    I'd be very grateful for any assitance
    eventually I intend to email out 3 seperate attachments at the same time,
    from a bank of about 10 files which are either pdf's or word doc's
    Dioxin

    Lets not go into my lack of Java training just yet :-P
         } catch (IOException ioex) {
             ioex.printStackTrace();was the block I was missing
    I'd also miswritten the problem code...cos I'd been fiddling with other commands
    mbp2.attachFile(bookingFilename);well it appears to compile... now to fire off a test email!
    cheers
    Dioxin

  • 4 Types of exception and the code to handle them

    Dear all,
    I would like to know wheter runtime exception, errors exception, unchecked exception and checked exception are classified as the 4 types of exception.
    What are the java coding of them? please help.

    There are two main families of exception in Java: checked and unchecked.
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • Must be caught or declared to be thrown...

    how would i go about something like that?
    import java.util.*;
    public class GameLauncher{
    public static void main( String [] args) {
         SellGame game = new SellGame();
              game.startGame();
    ____________________________________________________________________

    how would i go about something like that?I am guessing that your program will not compile... something like this:
    % cat HelloWorld.java
    public class HelloWorld {
        public static void main(String args[]) {
            System.out.println("Hello, world!");
            java.lang.Thread.sleep(500);
    % javac -g HelloWorld.java
    HelloWorld.java:5: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
            java.lang.Thread.sleep(500);
                                  ^
    1 errorRefer to this section of the Tutorial for an explanation:
    Exception Handling Statements
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/exception.html
    Hope this helps.
    "Troubleshooting Guide for J2SE 5.0",
    http://java.sun.com/j2se/1.5/pdf/jdk50_ts_guide.pdf

  • My function must be caught or declared to be thrown?

    hi again.
    so here's what's going on.
    i'm writing a class that contains a function that will be used as a part of a program. only one parameter will be passed, in this case, BAC.
    to test my program, i'm trying to write a simple main function to call the class. here's what it looks like:
    public static void main(String[] args) {
    String BAC = "teststring";
    findbac bac = new findbac();
    bac.findbac(BAC);
    the function i'm trying to call is findbac(String BAC) in class findbac.
    when i compile, i get the error message
    29: unreported exception java.io.IOException; must be caught or declared to be thrown
    bac.findbac(BAC);
    i just started java a few days ago so im not 100% familiar with the throw and catch terms.
    what should i do to make this work? thanks.

    thanks a bunch for the help. still a little confusing, but im gonna sit down and figure it all out tonight after i get home.
    and i tried putting in the code Valavet suggested, and it compiles now! but when i run it, i get a new error:
    java.lang.ArrayIndexOutOfBoundsException: 2
    at findit.findbac.findbac(findbac.java:108)
    at findit.findbackclass.main(findbackclass.java:37)
    Exception in thread "main"
    Java Result: 1
    the two lines of code are
    experiments[experimentnumber-1] = dataline.substring(beginningIndex, endIndex);
    and
    bac.findbac(BAC);
    respectively.
    what do they mean by array index out of bounds? i know my array index is correct.
    do {            //this do-while loop writes each experiment's result (as a string) to the experiments[] matrix.
                                    foundIndex = dataline.indexOf(comma, fromIndex);
                                    if (foundIndex >= 0) {
                                        experimentnumber++;
                                        fromIndex = foundIndex + 1;
                                    endIndex = fromIndex;
                                    if (experimentnumber >= 1){
                                        experiments[experimentnumber-1] = dataline.substring(beginningIndex, endIndex);
                                    beginningIndex = fromIndex;
                                } while (foundIndex >= 0);

  • Conn.rollback() must be caught or declared to be thrown

    Hi, I'm having problems compiling the following code
    private void toInsert(String insert_foo, int insert_bar) {
              InitialContext context = null;
              Connection conn = null;
              PreparedStatement pstmt= null;     
              try {
                   context = new InitialContext();
                   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/TestDB");
                   conn = ds.getConnection();
                   conn.setAutoCommit(false);
                   pstmt = conn.prepareStatement("INSERT into testdata values(?, ?)");
                   pstmt.setString(1, insert_foo);
                   pstmt.setInt(2, insert_bar);
                   pstmt.executeUpdate();
                   conn.commit();
                   conn.setAutoCommit(true);
                   pstmt.close();
                   pstmt = null;
                   conn.close();
                   conn = null;
                   context.close();
                   context = null;
              catch (Exception e) {
                   conn.rollback();
              finally {
                   if (pstmt != null) {
                        try { pstmt.close(); }          
                        catch (SQLException e) {;}     
                        pstmt = null;               
                   if (conn != null) {
                        try { conn.close(); }          
                        catch (SQLException e) {;}     
                        conn = null;               
                   if (context != null) {
                        try { context.close(); }     
                        catch (NamingException e) {;}     
                        context = null;               
         }I got this error when I try to compile the above;
    unreported exception java.sql.SQLException; must be caught or declared to be thrown
    conn.rollback();
    I search and read through a lot of posts here that rollback() could be used in the catch block but why I can't I compile it?
    Please help me out, thank you.
    puzzled....

    Is it similiar to factory methods? No.
    I've read up on this:
    http://www.javaworld.com/javaworld/javaqa/2001-05/02-qa-0511-factory.html?
    "small boy with a pattern" syndrome strikes again.
    Could you assist to help me in giving me guidelines
    for writing the database utilites class?
    Appreciated...
    public final class DatabaseUtils
        public static void close(Connection c)
            if (c != null)
                try
                    c.close();
                catch (SQLException e)
                      // print stack trace or, better yet, log the exception with Log4J
        // same for other close operations on ResultSet and Statement
        public void rollback(Connection c)
            if (c != null)
                try
                    c.rollback();
                catch (SQLException e)
                      // print stack trace or, better yet, log the exception with Log4J
    }%

  • Which type of users will be impacted

    Dears,
    which type of users will be impacted after increase new password parameters ?
    I tested that dialog users will need to reset the password and service users still could use old password to logon in front-end,
    but I don't konw how to confirm if system and communcation users are all impacted by new password parameters .
    Thanks.

    Hi Michael,
    Ideally password policies are application to dialog users only unless exceptions are specified against the SAP profile.
    Refer to SAP help for detailed information on the password policy parameters and exception details(if any).
    https://help.sap.com/saphelp_nw04/helpdata/en/22/41c43ac23cef2fe10000000a114084/content.htm
    Hope this helps.
    Regards,
    Deepak Kori

Maybe you are looking for