Generic throws clause causes unreported exception

I'm trying to pass a block to a ctor, which can throw an exception. The problem can be reproduced with this sample program.
interface Bar<X extends Exception> {
    void run() throws X;
public class Foo {
    public Foo() {}
    public <X extends Exception> Foo(Bar<X> bar) throws X {
        bar.run();
    public static <X extends Exception> Foo createFoo(Bar<X> bar) throws X {
        return createFoo2(bar); // ok
    public static <X extends Exception> Foo createFoo2(Bar<X> bar) throws X {
        Foo foo = new Foo();
        bar.run(); // ok
        return foo;
    public static <X extends Exception> Foo createFoo3(Bar<X> bar) throws X {
        return new Foo(bar);  // unreported exception X; must be caught or declared to be thrown
}createFoo and createFoo2 work fine, but createFoo3 fails to compile with javac. None of the examples raise a warning in IDEA. I'm running javac 1.5.0_07.
Is there a way to do this in Java 1.5, or is this a bug with javac?

BrianEgge wrote:
However, we know types inference works differently for methods vs constructors (15.12.2.8). This is why List<String> s = Collections.emptyList(); works, but List<String> s = new ArrayList<String>() generates an unchecked warning. Well, this is definitely not true.
According the the JLS, the throws clause shouldn't be handled differently.
8.8.5 Constructor Throws
The throws clause for a constructor is identical in structure and behavior to the throws clause for a method (�8.4.6).The JLS explicitely allows a constructor to be defined generic, and those parameters have a scope on the constructor definition including the parameter list (8.8.4 Generic Constructors).
Hence, I assume, this is a bug.

Similar Messages

  • AbstractTable model exception throws clause error?

    I want to display a JDialog whenever the user tries to enter a string when the column class is Double. To do this, I am trying to throw an exception from the setValueAt() method in my class that extends AbstractTable model. However, my code results in an "Exception StatisticsException is not compatible with throws clause in AbstractTableModel.setValueAt()". Any idea how I can work around this? Is there a better way to display a JDialog in this case? Thanks in advance.
    public void setValueAt(Object text, int rowIndex, int columnIndex)throws StatisticsException{
             if(variables[columnIndex].isDouble()){
                  try{
                       Double.parseDouble(text.toString());
                       Object[] temp = data.get(rowIndex);
                       temp[columnIndex] = text.toString();
                       data.remove(rowIndex);
                       data.add(rowIndex, temp);
                  }catch(NumberFormatException ex){
                       throw new StatisticsException("Numeric value required.");
             }else{
                  Object[] temp = data.get(rowIndex);
                  temp[columnIndex] = text.toString();
                  data.remove(rowIndex);
                  data.add(rowIndex, temp);
        }

    Ah, yes of course. In the midst of trying to account for data entry errors, I forgot that. The following revised code works just fine. Thanks.
        public void setValueAt(Object text, int rowIndex, int columnIndex){
              Object[] temp = data.get(rowIndex);
              temp[columnIndex] = text.toString();
              data.remove(rowIndex);
              data.add(rowIndex, temp);
        }

  • Purpose of throws clause in exception handling

    hi all,
    I have written a sample code for exception handling...please refer below....
    class a
    void fun() throws ArithmeticException
    int i=0;
    i=10/0;
    class exec
    public static void main(String a[])
    a a1=new a();
         try{a1.fun();}
         catch(ArithmeticException e){System.out.println("hi");}
    }

    I read the article...and came out with these points...
    1..If method is throwing an unchecked exception (as in this case) then there is no need for throws clause, if you are not catching it then and there only.....
    2...if a method is throwing a checked exception then either you need to catch it then and there only or you must specify a throws clause for the same in function definition......*And the purpose of not catching it then and there only is*
    "For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it."
    M I RIGHT??

  • Unreported exception

    hi all,
    what is the problem to cause the error?? please teach me. thanks.
    C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:76: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    Connection c = DriverManager.getConnection(
    ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:79: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    Statement s = c.createStatement();
    ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:140: unreported exception java.sql.SQLException; must be caught or declared to be thrown
    s.executeUpdate(sql);
    ^
    An error occurred at line: 9 in the jsp file: /jsp/HMC/HTML/testDL3.jsp
    Generated servlet error:
    C:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\examples\jsp\HMC\HTML\testDL3_jsp.java:154: unreported exception java.sql.SQLException; must be caught or declared to be thrown
         c.close();
    ^

    Either put your code in try / catch(SQLException)/ finally blocks, either declare the method where your code resides to throw a SQLException, using the throws clause.
    Google for any JDBC code and you'll see countless examples on how to do this.

  • 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").

  • How to slove follwoing error "Unreported exception java.io.IOException;"

    Currently I'm using following:
    XP Professional
    J2sdk1.4.2_01
    Xerces-2_5_0
    Xalan-j_2_5_1
    Jakarta-tomcat-4.1.27
    Jdom-b9
    Current Classpath setting
    User variables
    PATH = c:\bmrt2.5\bin; c:\j2sdk\bin;%PATH%;%JAVA_HOME%\bin;
    CLASSPATH=.;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;
    c:\xerces\xercesSamples.jar;c:\xalan\xercesImpl.jar;c:\xalan\xmlapis.jar;c:\xalan\xalan.jar;c:\tomcat\lib\webserver.jar;c:\tomcat\lib\jasper.jar;c:\tomcat\lib\xml.jar;c:\tomcat\common\lib\serlet.jar;c:\tomcat\lib\tools.jar; c:\tomcat\lib\tools.jar;c:\jdom\build\jdom.jar;
    CATALINA_HOME= c:\tomcat
    JAVA_HOME= c:\j2sdk
    System variables
    PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;
    c:\j2sdk\bin;%Path%;%JAVA_HOME%\bin;
    CLASSPATH=.;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;
    c:\xerces\xercesSamples.jar;c:\xalan\xercesImpl.jar;c:\xalan\xmlapis.jar;c:\xalan\xalan.jar;c:\tomcat\lib\webserver.jar;c:\tomcat\lib\jasper.jar;c:\tomcat\lib\xml.jar;c:\tomcat\common\lib\serlet.jar;c:\tomcat\lib\tools.jar; c:\tomcat\lib\tools.jar;
    CATALINA_HOME= c:\tomcat
    JAVA_HOME= c:\j2sdk
    Program
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.jdom.*;
    import org.jdom.Element;
    import org.jdom.Document;
    import org.jdom.output.XMLOutputter;
    import org.jdom.input.SAXBuilder;
    import org.jdom.Attribute;
    import java.util.List;
    public class AddToList extends HttpServlet
         public Document getDocument(File sourceFile, PrintWriter errorsOut)
              try
                   SAXBuilder builder = new SAXBuilder();
                   Document document = builder.build(sourceFile);
                   return document;
              catch(JDOMException e)
                   errorsOut.print("there was a problem building the document: " e. getMessage()"<br/>"+ "Returning blank document.");
                   return new Document(new Element("blank"));
         public void saveDocument(Document saveDoc, File saveFile, PrintWriter errorsOut)
              try
                   FileOutputStream outStream= new FileOutputStream(saveFile);
                   XMLOutputter outToFile= new XMLOutputter(" ",true);
                   outToFile.output(saveDoc, outStream);
                   outStream.flush();
                   outStream.close();
              catch (IOException e)
                   errorsOut.print("Can't save order.xml: " + e.getMessage()+"<br />");
         public void addItem(Element orderElement, String product_id, String quant)
              Element newItem =new Element("item");
              newItem.setAttribute("product_id", product_id);
              Element quantity =new Element("quantity");
              quantity.addContent(quant);
              newItem.addContent(quantity);
              orderElement.addContent(newItem);
         public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException
              String thisProduct_id=request.getParameter("addProduct_id");
              String thisQuantity=request.getParameter("addQuantity");
              response.setContentType("text/html");
              PrintWriter out= response.getWriter();
              out.print("Adding "+ thisQuantity + "of item to chart "+ thisProduct_id +" ... ");
              File orderFile = new File ("file:///c:/jdk1.3/orders.xml");
              if(!orderFile.exists())
                   out.print("Creating ordersrocks....<br />");
                   Element root= new Element("orders");
                   root.addContent(" ");
                   Document document = new Document(root);
                   saveDocument (document, orderFile, out);
              else
                   out.print("Orders File Exists.");
              Document document =getDocument(orderFile, out);
              HttpSession session =request.getSession(true);
              String session_id= session.getId();
              Element root =document.getRootElement();
              List orders =root.getChildren();
              int num_orders =orders.size();
              boolean orderExists =false;
              int orderIndex =0;
              for(int i=0; i<num_orders; i++)
                   Element iOrder=(Element)orders.get(i);
                   String iOrder_id=iOrder.getAttributeValue("order_id");
                   if (iOrder_id.equals(session_id))
                        orderExists=true;
                        orderIndex=i;
                        break;
              if(!orderExists)
                   Element order =new Element("order");
                   order.setAttribute("order_id", session_id);
                   Element status =new Element("order_status");
                   status.setText("open");
                   order.addContent(status);
                   addItem(order, thisProduct_id, thisQuantity);
                   root.addContent(order);
              else
                   Element thisOrder=(Element)orders.get(orderIndex);
                   boolean itemExists=false;
                   int itemIndex =0;
                   List items =thisOrder.getChildren("item");
                   int num_items =items.size();
                   for(int i=0; i<num_items; i++)
                        Element iItem=(Element)items.get(i);
                        String iProduct_id =iItem.getAttribute("product_id").getValue();
                        if(iProduct_id.equals(thisProduct_id))
                             itemExists =true;
                             itemIndex =i;
                             break;
                   if(itemExists)
                        Element thisItem=(Element)items.get(itemIndex);
                        String currentQuantity= thisItem.getChildText("quantity");
                        int newQuantity = Integer.parseInt(currentQuantity)+ Integer.parseInt(thisQuantity);
                        String strQuantity= new String().valueOf(newQuantity)+1;
                        thisItem.getChild("quantity").setText(strQuantity);
                   else
                        addItem(thisOrder, thisProduct_id, thisQuantity);
              saveDocument (document, orderFile, out);
         public void doPost(HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException
              doGet(request, response);
    When I compile above program, it gives me following error.
    Error
    C:\tomcat\webapps\book\WEB-INF\classes>javac AddToList.java
    AddToList.java:19: unreported exception java.io.IOException; must be caught
    or declared to be thrown
    Document document = builder.build(sourceFile);
    ^
    1 error
    Any help regarding this will be appreciated
    Thank you
    Rocks

    Obadare
    Thank for your help, my program compile successfully. But now I�m facing different kind of error on Tomcat; why it gives me following error and how do I solve it
    http://localhost:8080/rock/servlet/AddToList
    Following Error generate by Tomcat:
    Http Status 500-
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: Cannot allocate servlet instance for path /rock/servlet/AddToList
         at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:435)
         at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
    (ApplicationFilterChain.java:247)
    root cause
    java.lang.NoClassDefFoundError: org/jdom/JDOMException
         at java.lang.Class.newInstance0(Native Method)
         at java.lang.Class.newInstance(Class.java:237)
         at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:903)
         at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:668)
         at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:416)
         at org.apache.catalina.servlets.InvokerServlet.doGet(InvokerServlet.java:180)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
    (ApplicationFilterChain.java:247)
    The following is my configuration
    Classpath= .;c:\xalan\bin\xalan.jar;c:\xalan\bin\xml-apis.jar;c:\xerces\xmlParserAPIs.jar;c:\xerces\xercesImpl.jar;c:\tomcat\common\lib\servlet.jar;c:\jdom\build\jdom.jar;
    Java_Home=c:\jdk1.3
    Catalina_Home=c:\tomcat
    Server.xml
    <Engine name="Standalone" defaultHost="localhost" debug="0">
    <Host name="localhost" debug="0" appBase="webapps"
    unpackWARs="true" autoDeploy="true">
    <Context path="/rock" docBase="rock" debug="0"
    reloadable="true" crossContext="true">
    P.S When I try to build javadoc it give me following error:
    C:\jdom>build javadoc
    JDOM Build System
    Building with classpath c:\jdk1.3\lib\tools.jar;.\lib\ant.jar;.\lib\xml-apis.jar
    ;.\lib\xerces.jar;
    Starting Ant...
    Buildfile: build.xml
    [javadoc] Constructing Javadoc information...
    [javadoc] Building tree for all the packages and classes...
    [javadoc] Building index for all the packages and classes...
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] Building index for all classes...
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.Transformer
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.Transformer
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.Transformer JAXP TrAX Transformer
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: javax.xml.
    transform.TransformerFactory#getFeature
    [javadoc] javadoc: warning - Tag @link: Class or Package not found: java.lang.
    Double#NaN
    [javadoc] Generating C:\jdom\build\apidocs\stylesheet.css...
    [javadoc] 10 warnings
    BUILD SUCCESSFUL
    Total time: 12 seconds

  • Underscore causing an exception in a toolbar

    //  I'm using Netbeans 7.4 release candidtate 2
    //  1)  Start the JavaFx Ensemble program - thank you very much.  It has saved me many hours.
    //  2)  In Ensemble Click on "Hidden Split Pane".
    //  3)  Click the "Source Code" tab.
    //  4)  Click the "Save Netbeans project".
    //  5)  Replace HiddenSplitPaneSample.java with this code (see below).
    //  6)  After starting: click the "double arrow" twice (maybe three times) to display the options in the center pane.
    //  7)  The second time you should get the exception.  (See Netbeans output window.)
    //  8)  You get the double arrow because dividerPositions() is set too small; but that may be the way some user
    //      would have things "split".
    //  Why this is important to me.  I included a phony getWord() method (see below).  In my app getWord() will
    //  actually go to disk and get a word, in the human language that the user has selected somewhere else.
    //  Example:    if they have English selected then getWord( "Add_One" ) will return "Add One" and display it as the buttons text.
    //              if they have Chinese selected then getWord( "Add_One" ) will return "Chinese equivalent of Add One" and display it as the buttons text.
    //              If there is no replacement in the file then getWord( "Add_One" ) will return "Add_One".
    //  The question is why does the underscore cause an exception?  I could easily replace the under score with
    //  a dash (see below) because that doesn't cause the exception. But that begs the question what will happen
    //  when I'm using Chinese, Japanese, or Hindi?  Is there a stray character here and there that will cause
    //  this exception?
    //  Notice also that it has removed my underscore: "Add_One" becomes "AddOne".
    * Copyright (c) 2008, 2012 Oracle and/or its affiliates.
    * All rights reserved. Use is subject to license terms.
    import javafx.application.Application;
    import javafx.geometry.HPos;
    import javafx.geometry.VPos;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ScrollPane;
    import javafx.stage.Stage;
    import javafx.scene.control.SplitPane;
    import javafx.scene.control.SplitPaneBuilder;
    import javafx.scene.control.ToolBar;
    import javafx.scene.control.ToolBarBuilder;
    import javafx.scene.layout.Pane;
    import javafx.scene.layout.RegionBuilder;
    import javafx.scene.layout.VBox;
    public class HiddenSplitPaneSample extends Application {
        ToolBar     standardToolbar     = null;
        ScrollPane  scrollPane          = new ScrollPane    ();
        class MyPane extends Pane   {
            @Override
            protected void layoutChildren() {
                super.layoutChildren   ();
                double  w   = getWidth  ();
                double  h   = getHeight ();
                double  ph  = standardToolbar.getHeight();
                layoutInArea    ( standardToolbar,  0,  0,  w, ph,    0,  HPos.CENTER,    VPos.CENTER );
                layoutInArea    ( scrollPane,       0,  0+ph,   w, h-ph,    0,  HPos.LEFT,    VPos.CENTER );
        private String  getWord ( String wordToGet )    {
            return  wordToGet;
        private void init(Stage primaryStage) {
            MyPane  pane1   = new MyPane    ();
                    pane1   .setPrefWidth   ( 400 );
                    pane1   .setPrefHeight  ( 400 );
            standardToolbar = ToolBarBuilder.create().build();
                standardToolbar     .setPrefHeight      ( 30 );
                standardToolbar     .setMinHeight       ( 30 );
                standardToolbar     .setMaxHeight       ( 30 );
                pane1.getChildren() .add( standardToolbar );
                Button  addOneButton    = new Button    ( getWord( "Add_One"    ) );
                Button  addTwoButton    = new Button    ( getWord( "Add_Two"    ) ); 
                Button  addThreeButton  = new Button    ( getWord( "Add_Three"  ) );
                Button  addFourButton   = new Button    ( getWord( "Add_Four"   ) ); 
                //Button  addOneButton    = new Button    ( getWord( "Add-One"    ) );
                //Button  addTwoButton    = new Button    ( getWord( "Add-Two"    ) ); 
                //Button  addThreeButton  = new Button    ( getWord( "Add-Three"  ) );
                //Button  addFourButton   = new Button    ( getWord( "Add-Four"   ) ); 
                standardToolbar .getItems().add ( addOneButton      );
                standardToolbar .getItems().add ( addTwoButton      );
                standardToolbar .getItems().add ( addThreeButton    );
                standardToolbar .getItems().add ( addFourButton     );
            VBox    vbox    = new VBox  ();
            scrollPane  .setContent     ( vbox );
            scrollPane  .setFitToWidth  ( true );
            pane1   .getChildren().add     ( scrollPane );
            Group root = new Group();
            primaryStage.setScene(new Scene(root));
            String hidingSplitPaneCss = HiddenSplitPaneSample.class.getResource("HiddenSplitPane.css").toExternalForm();
            final SplitPane splitPane = SplitPaneBuilder.create().id("hiddenSplitter").items(
                    RegionBuilder.create().styleClass("rounded").build(),
                    pane1,//RegionBuilder.create().styleClass("rounded").build(),
                    RegionBuilder.create().styleClass("rounded").build()).dividerPositions(new double[]{0.33, 0.50}).build();
            splitPane.getStylesheets().add(hidingSplitPaneCss);
            root.getChildren().add(splitPane);
        @Override public void start(Stage primaryStage) throws Exception {
            primaryStage.setX      ( 0 );
            primaryStage.setY      ( 0 );
            primaryStage.setWidth  ( 500 );
            primaryStage.setHeight ( 500 );
            init(primaryStage);
            primaryStage.show();
        public static void main(String[] args) { launch(args); }

    The underscore is being parsed as an indicator that the next character should be a mnemonic, and the underscore is then stripped. This happens by default on Buttons, but not on Labels.
    See the API in the Labeled class. You can either turn parsing off, or you can use two underscores to represent one underscore.

  • Javadoc @throws clause at a class level for all methods

    hello
    If all my class's methods throw the same RuntimeException for the same reasons, is there a way to put a @throws clause at class level?
    I mean, I don't want to duplicate my comments for each of the methods I have. Say I want to add extra information... It would be a pain to copy paste same
    comment for all the methods.
    Thx in advance, any help welcomed :)

    kux wrote:
    hello again
    first of all, love your replay :). Nice to see people with good sense of humor :D
    Ok, I made the story shorter. Of course I don't throw a raw RuntimeException. What I have is a subclass of RuntimeException. Basicly all my methods use a sql Connection and do a certain querry on a database. What I do is that I don't let checked SQLException propagate through my methods because the clients of the persistance layer should not be required to handle the low level sql exeptions.Correct!
    Instead I catch them and rethrow them as DAOExceptions that SUBCLASS RuntimeException. Unusual... but... Hmmm... I can't say that's actually "bad practice", per se, but DAOException is traditionally a checked exception type thrown only from the very top of the DAO specifically so that clients must catch (or explicitly throw) it... Hmmm..
    Basicly I used sun's DAO pattern: http://java.sun.com/blueprints/patterns/DAO.html.
    That's be The GOF's pattern... but yeah, good choice.
    I made the question shorter because this is not the point. The question was about javadoc, not my programming practices :)But, but, but...
    Ok... Ah... Ok.... Ummm, No. At least Not That I Know Of... BUT, what you can do is summarise your exception handling strategy once in the class summary section, and just reference it in each throws clause... you can stick intra-page links in java doc (I've seen them, just not sure how they're done, I think the syntax is something like {@link:anchor}... but that's just something I once saw somewhere... not gospel.
    Also, if a method has throws DAOExceptions for an "odd" reason (like invalid data retrieved successfuly from the database (yes, it happens)) then you can still document that case in the method.
    If your exception handling is really worth talking about then an external article referenced in the class summary. We use a wiki (http://en.wikipedia.org/wiki/DokuWiki) for such purposes, and many others including research schedules and papers, and (increasingly) design doco, even though that's outside the "official process" we find the wiki so much more convenient (i.e. searchable), especially since it's become possible to convert (simple) word-doc's straigth to wiki markup.
    But, but, but... Programming practices are so much more interesting than documentation... who ever complained about in the documentation (besides me I mean).
    Cheers mate. Keith.

  • 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");
      }

  • What's the role of 'throws' clause in method overriding

    I'm getting error when subclass "Parser" overrides method 'getInt()' which throws Exception but super class version don't. It is compiling without error when vice versa is true i.e., super class version throws exception but sub class version don't throw exception.
    What's the role of 'Throws' clause in method overriding?
    What's the rationale with the output of following program?
    class Parser extends Utils {
       public static void main(String [] args) {
         System.out.print(new Parser().getInt("45"));
      int getInt(String arg) throws Exception{
         return Integer.parseInt(arg);
    class Utils {
       int getInt(String arg)  { return 42; }
    }

    karthikbhuvana wrote:
    I'm getting error when subclass "Parser" overrides method 'getInt()' which throws Exception but super class version don't. It is compiling without error when vice versa is true i.e., super class version throws exception but sub class version don't throw exception.
    What's the role of 'Throws' clause in method overriding?
    What's the rationale with the output of following program?
    class Parser extends Utils {
    public static void main(String [] args) {
    System.out.print(new Parser().getInt("45"));
    int getInt(String arg) throws Exception{
    return Integer.parseInt(arg);
    class Utils {
    int getInt(String arg)  { return 42; }
    Supose you do:
    Utils u = new Parser();
    int i = u.getInt("XX");This would throw a NumberFormatException, which is a checked exception, yet the compiler doesn't know this because Util.getInt() has no throws clause. Such a loophole would defeat the whole point of having throws clauses.
    So a method can only implement or override another if the throws clause on the interface or superclass admits the possibility of throwing every exception that the implementing method can throw, thus code which calls the method from a superclass or interface reference doesn't get any unexpected exceptions.

  • Unreported exception--Need Help

    I can't understand why is this not working:
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;
    public class Slanje {
         public void infos(String host,String from,String to,String subject,String messagetext){
    /*String host="";
    String from="";
    String to="";*/
    // Get system properties
    Properties props = System.getProperties();
    // Setup mail server
    props.put("mail.smtp.host", host);
    // Get session
    Session session = Session.getDefaultInstance(props, null);
    // Define message
    MimeMessage message = new MimeMessage(session);
    // Set the from address
    message.setFrom(new InternetAddress(from));
    // Set the to address
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to));
    // Set the subject
    message.setSubject(subject);
    // Set the content
    message.setText(messagetext);
    // Send message
    Transport.send(message);
    I'm making email client and want to make methods to be called when wanting to make message to be send

    I presume you're getting a compiler error regarding the unreported exception, right? That means you need to put your method calls that throw exceptions in a try/catch block. For example, props.put() throws NullPointerException, so you need a catch statement for that. The other method calls may have similar needs.
    Steve

  • Unreported Exception java.lang.InstantiationException

    Dear Friends,
    I am developing javabean connectivty for inserting records to mysql database from jsp. when i try to compile java bean program. It gives an error like unreported Exception java.lang.InstantiationException: Must be caught or declared to be thrown*. This is my mode. Please anyone help to solve this error. if you find any error in my code, please suggest me. Thanks in advance.
    package com.webdeveloper.servlets;
    import java.sql.*;
    import java.io.*;
    public class InsertBean {
    private String dbURL = "jdbc:mysql://localhost:3306/test";
    private Connection dbCon;
    private Statement st;
    String dbuser = "root";
    String dbpass = "admin";
    String Name = null;
    String Address = null;
    String Zip = null;
    public InsertBean() {
    super();
    public String getName() {
    return this.Name;
    public String getAddress() {
    return this.Address;
    public String getZip() {
    return this.Zip;
    public void setName(String pname) {
    this.Name = pname;
    public void setAddress(String paddress) {
    this.Address = paddress;
    public void setZip(String pzip) {
    this.Zip = pzip;
    public void doInsert() throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver").newInstance();//it gives error in this line
    dbCon = DriverManager.getConnection(dbURL,dbuser,dbpass);
    Statement s = dbCon.createStatement();
    String sql = "Insert into Person values ('" + this.Name;
    sql = sql + "', '" + this.Address + "', " + this.Zip;
    sql = sql + ")";
    int insertResult = s.executeUpdate(sql);
    dbCon.close();
    }

    Dear BalusC,
    Thanks for your suggestion. I used try catch block also. But it still gives same error. I have modified my following code. Is there any thing wrong in my code? Please give me your suggestion. Thankyou.
    // Java Document
    package com.webdeveloper.servlets;
    import java.sql.*;
    import java.io.*;
    public class InsertBean {
    private String dbURL = "jdbc:mysql://localhost:3306/test";
    private Connection dbCon;
    private Statement st;
    String dbuser = "root";
    String dbpass = "admin";
    String Name = null;
    String Address = null;
    String Zip = null;
    public InsertBean() {
    super();
    public String getName() {
    return this.Name;
    public String getAddress() {
    return this.Address;
    public String getZip() {
    return this.Zip;
    public void setName(String pname) {
    this.Name = pname;
    public void setAddress(String paddress) {
    this.Address = paddress;
    public void setZip(String pzip) {
    this.Zip = pzip;
    public void doInsert() throws ClassNotFoundException, SQLException {
         try{
         Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbCon = DriverManager.getConnection(dbURL,dbuser,dbpass);
    Statement s = dbCon.createStatement();
    String sql = "Insert into Person values ('" + this.Name;
    sql = sql + "', '" + this.Address + "', " + this.Zip;
    sql = sql + ")";
    int insertResult = s.executeUpdate(sql);
         catch(Exception e){
         System.out.println("error occured :" + e);
         dbCon.close();
    }

  • FileReader - Unreported exception

    Me again!!
    Having problems with FileReader - here's my code:
    void button1_actionPerformed(ActionEvent e)
        FileReader file = new FileReader ("d:\\a.txt");
        BufferedReader inputFile = new BufferedReader(file);
        String input = inputFile.readLine();
        textField1.setText(input);
      }Getting two unreported exception errors - how can I get rid of those?
    NB. java.io.*; is imported...
    Please help!!
    Thanks,
    Sam

    If you look at the API docs, you'll see that many methods throw exceptions. Normally you'll want to use try/catch blocks to deal with exceptions when they occur.
    If you look at the constructor for FileReader, you'll see that is throws a FileNotFoundException. If you look at the readLine() method of class BufferedReader you'll see that it throws an IOException. As FileNotFound is a subclass of IO then you can deal with them both in the same catch block:
    try
        FileReader file = new FileReader ("d:\\a.txt");
        BufferedReader inputFile = new BufferedReader(file);
        String input = inputFile.readLine();
        textField1.setText(input);
    catch(IOException ioex)
        System.out.println(ioex.toString());
    }

  • Unreported exception during connection

    hi all,
    I am trying to connect to the database.I am using
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection = DriverManager.getConnection(driver+"@"+host+":"+port+":"+serverID,userID,password);
    statement = connection.createStatement();
    but i am getting the following error.
    Error(105,16): unreported exception: java.lang.ClassNotFoundException; must be caught or declared to be thrown
    I tried making the following changes:
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    connection = DriverManager.getConnection(driver+"@"+host+":"+port+":"+serverID,userID,password);
    statement=connection.createStatement();
    but got the following error
    Error(110,55): cannot access class oracle.jdbc.driver.OracleDriver; file oracle\jdbc\driver\OracleDriver.class not found
    I am using the jdevloper9i rc2 and have been working on this project for some time now but didnt got any of the above errors in the different modules of the project when i used any of the above statements,The above errors never occured before.
    Also i did checked my classpath for the classes.jar which was set as
    c:/<jdev direc>/jdbc/lib/classes12.jar
    kindly suggest..
    regards,
    nikhil

    Nikil:
    hi all,
    I am trying to connect to the database.I am using
    Class.forName("oracle.jdbc.driver.OracleDriver");
    connection = DriverManager.getConnection(driver+"@"+host+":"+port+":"+serverID,userID,password);
    statement = connection.createStatement();
    but i am getting the following error.
    Error(105,16): unreported exception: java.lang.ClassNotFoundException; must be caught or declared to be thrownThis is because Class.forName can throw a ClassNotFoundException. Wrap your code with try/catch as in
       try
          Class.forName ...
       catch(Exception ex)
          // exception handling
       }==================
    I tried making the following changes:
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    connection = DriverManager.getConnection(driver+"@"+host+":"+port+":"+serverID,userID,password);
    statement=connection.createStatement();
    but got the following error
    Error(110,55): cannot access class oracle.jdbc.driver.OracleDriver; file oracle\jdbc\driver\OracleDriver.class not found
    I am using the jdevloper9i rc2 and have been working on this project for some time now but didnt got any of the above errors in the different modules of the project when i used any of the above statements,The above errors never occured before.
    Also i did checked my classpath for the classes.jar which was set as
    c:/<jdev direc>/jdbc/lib/classes12.jarLook for classes12.jar on your C drive and set your classpath with the correct file name. The location has changed over time.
    Thanks.
    Sung
    kindly suggest..
    regards,
    nikhil

Maybe you are looking for