Catch Statement, Help!!!

I need help with a catch statement that will give an error message when Letters are put in, i need this as im only working with numebers, Heres what i have done already. When i build the code i always get
";" expected
Thanks for your Help
jMenuKmperHourMileActionPerformed(java.awt.event.ActionEvent e)
try
String Number = ToBeConverted.getText();
double amount = new Double(Number).doubleValue();
total = (amount*.621371192);
Converted.setText("= " + total);
ToBeConverted.setEditable(false);
catch(NumberFormatException nfx)
Converted.setText(Number + " is not a valid number!");
}

Your try/catch statement is bad. You have too many { } brackets in there.
The format should be
try{
  // code which throws Exceptions
  String Number = ToBeConverted.getText();
  double amount = new Double(Number).doubleValue();
  total = (amount*.621371192);
  Converted.setText("= " + total);
  ToBeConverted.setEditable(false);
catch(NumberFormatException nfx){
  // error handler
  Converted.setText(Number + " is not a valid number!");
}

Similar Messages

  • Control flow: catch statement

    Hi there!,
    Need to know where the control passes if an error is caught in a catch statement.
    Suppose no alternative error handling code has been specified. Where would control go if a terminal error occured? Would it just carry on to the next statement in the general flow or would it terminate the application/applet. By terminal, i mean something like getParameter() returning null etc..
    Any help that sheds light on this is appreciated greatly.
    To make this clearer, how would the program know when to exit a try catch statement if it falls into a catch statement that gave a nonsensical value?

    You should be careful with your terms, "an error is
    caught" has a very specific meaning in Java. Errors
    (instances of java.lang.Error and it's subclasses)
    should not be caught (that is, with a try-catch
    statement) in your code because they signal more
    serious problems than usual (like ClassNotFoundError,
    LinkageError, VirtualMachineError, and so on), not in
    switch statements or otherwise.In certain situations they should be caught.
    If I create a stand alone app with a client GUI it doesn't matter to the user if a null pointer exception, because of programmer error, occurs in the database layer. But they are going to get real upset if the app just abruptly exits which is what is going to happen if the GUI layer doesn't catch all of the exceptions. And although it is possible that one of those exceptions makes it impossible to do anything at all, it is much more likely that the GUI can at least display a message to the user before exiting. And write the stack trace to a file as well.
    This is true at the interface between any two layers. And some applications will be able to continue. I certainly don't want a J2EE server exiting because one of the new beans isn't working correctly. It won't stop the other beans from working.

  • Infinite loop in a catch {} statement, should be simple

    Hi, I'm trying to take integer input from the console using a Java Scanner object, and I enter an infinite loop if there is an IO error inside the catch statement. Please let me know if you know what I'm doing wrong:
    do
    try
    Problem = false; //this is a bool
    start = Input.nextInt(); // Input is a Scanner, start is an Intenger
    catch (Exception IOException) {
         Problem = true;
         System.out.println("Bad value.\n");
         //The infinite loop is inside this statement.
    while (Problem == true);
    This code block is intended to take integer input, then, if there's an IO error, try to do it again, indefinitely, until it has successfully given Start a value. As it stands, if executed, if there is not an IO error, it works; if there is an IO error it enters an infinite loop in the catch statement. Please forgive my incompetence, any help is appreciated :)

    Hi, thanks for the advice to both of you, your suggestion that it is stuck seems to be correct.
    I add to the catch statement:
    Input = new Scanner(System.in);
    To reset it, and it works now. This is probably not the best way to do things, but I'm just a student and it's for a homework assignment that does not require try / catch / for so it works for this, thank you for the help! :)

  • Exception Handling after the Catch Statement

    Hi every one,
    How to handle the exceptions after Catch Statement.
    What does a catch statement can do?
    Regards,
    Johny

    Hi,
    Check this link:
    http://help.sap.com/saphelp_nw70/helpdata/en/a9/b8eef8fe9411d4b2ee0050dadfb92b/content.htm
    http://help.sap.com/saphelp_nw70/helpdata/en/cf/f2bbce142c11d3b93a0000e8353423/content.htm
    Regards
    Adil

  • "catch is unreachable" compiler error with java try/catch statement

    I'm receiving a compiler error, "catch is unreachable", with the following code. I'm calling a method, SendMail(), which can throw two possible exceptions. I thought that the catch statements executed in order, and the first one that is caught will execute? Is their a change with J2SE 1.5 compiler? I don't want to use a generic Exception, because I want to handle the specific exceptions. Any suggestions how to fix? Thanks
    try {
    SendMail(....);
    } catch (MessagingException e1) {
    logger.fine(e1.toString());
    } catch (AddressException e2) {
    logger.fine(e2.toString());
    public String SendMail(....) throws AddressException,
    MessagingException {....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I found the problem:
    "A catch block handles exceptions that match its exception type (parameter) and exception types that are subclasses of its exception type (parameter). Only the first catch block that handles a particular exception type will execute, so the most specific exception type should come first. You may get a catch is unreachable syntax error if your catch blocks do not follow this order."
    If I switch the order of the catch exceptions the compiler error goes away.
    thanks

  • Biginner's question about catch statement

    hi im just a biginner
    normally u guys write catch statement like
    catch (FileNotFouldException exception)
    System.out.println (exception);
    something like that . but what is the exception here
    is it object name? or class name or what
    i mean the word exception after FileNotFoundException
    i just don't understand

    It's the type of the exception to which the catch block should apply.
    You could have this:
    try {
      // stuff
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    } catch (IOException ioe) {
      ioe..printStackTrace();
    } catch (NumberFormatException nfe) {
      nfe.printStackTrace();
    } catch (Exception x) {
      ex..printStackTrace();
    }Note that FNFE extends IOE, so if the IOE is caught first, the FNFE would be caught in that block too. That's why you catch the general Exception last - if you do it at all.

  • Jumping to a catch statement?

    hi, if I have the following code:
         private String getDefaultReportName(){
              String reportFolder = "Data\\Report_Name";
              FileInputStream FIS;
              //File reportNameFile;
              try {
                   File folder = new File(reportFolder); //check to see if the folder exists first!
                   if(folder.exists()){
                                  //then do some stuff
                             }//end if
                             else{
                                 //if this happens, I want to jump to the catch clause automatically...
                              }//end else
              }//end try
              catch (Exception e) {
                   return "Report";
         }I found that, in my code, i have used the 'return "Report";' line often and I would like to
    just jump straight to the catch statement if that is possible. I am sure it is, but I don't
    know how off the top of my head. How can I jump straight to a catch clause from a try
    block? thanks!

    I don't know what that's supposed to be doing, or
    what point you're trying to make, but it looks like
    the wrong way to use/handle exceptions.A coworker at a previous job called exceptions (we were writing in Ada) "glorified GOTO" (complaining about how another coworker used it too liberally). I believe that would apply in this case.

  • Regards catch statement

    Is there any thing worng in my catch statements .because when i do debug the curser not catching the catch statements
    TRY.
           CALL METHOD z_co_ifoasy_01_sa_gl=>execute_asynchronous
              EXPORTING
                output = gv_zsafe_mt_acc_gl_posting01.
          CATCH cx_ai_system_fault INTO s_exception.
          CATCH cx_ai_application_fault INTO s_exception_app.
        ENDTRY.
       IF ( s_exception IS  INITIAL AND s_exception_app IS INITIAL )
          MESSAGE i007.
        ELSE.
          PERFORM update_log_table.
          COMMIT WORK.
          MESSAGE i009. "Message sent to XI".
        ENDIF.
      ENDIF.

    hi,
        What type of Exceptions you want to catch in Proxy?
         Try to do commit work before you read exception variables for text and code.
    Follow this process:
    Proxy call
    catch exception
    commit work.
    Use Exception variale to read details.
    If you want to check that RFC Destination that pings your PI server is fine or not.
    Call FM: BDL_SERVER_PING
    to check if your PI server is down.
    Regards,
    Anurag Garg

  • Which catch statement, returns null

    just wanted to if there is any catch statement which returns if the file is null
    something like
    catch(NullPointException ex){
    }

    Ashish.Uppin wrote:
    just wanted to if there is any catch statement which returns if the file is null
    something like
    catch(NullPointException ex){
    Can I catch a null pointer exception? Yes.
    Do I? No
    Can you? Probably not.

  • Regards Catch statements

    Is there any thing worng in my catch statements .because when i do debug the curser not catching the catch statements
    TRY.
    CALL METHOD z_co_ifoasy_01_sa_gl=>execute_asynchronous
    EXPORTING
    output = gv_zsafe_mt_acc_gl_posting01.
    CATCH cx_ai_system_fault INTO s_exception.
    CATCH cx_ai_application_fault INTO s_exception_app.
    ENDTRY.
    IF ( s_exception IS INITIAL AND s_exception_app IS INITIAL )
    MESSAGE i007.
    ELSE.
    PERFORM update_log_table.
    COMMIT WORK.
    MESSAGE i009. "Message sent to XI".
    ENDIF.
    ENDIF.

    Try like below...
    TRY.
    CALL METHOD z_co_ifoasy_01_sa_gl=>execute_asynchronous
    EXPORTING
    output = gv_zsafe_mt_acc_gl_posting01.
    CATCH cx_ai_system_fault INTO s_exception.
    lv_exception = 'X'.
    CATCH cx_ai_application_fault INTO s_exception_app.
    IF ( lv_exception IS INITIAL AND s_exception_app IS INITIAL )
    MESSAGE i007.
    ELSE.
    PERFORM update_log_table.
    COMMIT WORK.
    MESSAGE i009. "Message sent to XI".
    ENDIF.
    ENDTRY.
    Edited by: Veeranji Reddy on Aug 7, 2009 5:15 PM

  • Code too large for try statement - help :(

    Please help :(
              We are migrating our project from an older technology, Kiva from netscape
              (and about time we migrate) . Kiva uses template evaluation similar to
              jakarta velocity. So the fastest way we found was to translate kiva
              templates to JSPs via perl script. All is working fine except a bunch of
              JSPs which are too large for the compiler to handle. If we were not
              migrating and instead wroking from scratch we would have simply made the
              JSP's size smaller and used jsp:include, but in this case it will involve a
              lot of effort as that means changing a lot of business code.
              Basically what we get is "code too large for try statement". Is there anyway
              we can tell weblogic to put smaller code fragments in try/catch when it
              converts a JSP into java code.
              

              Haider,
              Have you seen the following Sun Bug Parade posting
              http://developer.java.sun.com/developer/bugParade/bugs/4210912.html
              Additionally, you may want to try the '-noTryBlocks' jsp compiler switch and see
              if it makes a difference
              See the following 6.1 URL
              http://edocs.bea.com/wls/docs61/jsp/reference.html#57805
              Chuck Nelson
              DRE
              BEA Technical Support
              

  • Prepared statement help

    Hello all!
    I am trying to get this prepared statement to work but am getting an error that I cant understand.
    Basically I have a class file that the ps resides in. I am calling the ps from a jsp.
    Here is the code:
    public void recordUsage(String userid, String ipaddress, String page, String filename)
           String insertStatement = "INSERT INTO usageLog(userId,ipAddress, localTime, page, fileName) VALUES(?,?,?,?,?)";
                try
                {   java.util.Date currentDate=new java.util.Date();//Create a date object for the timestamp
                    java.sql.Timestamp ts=new java.sql.Timestamp(currentDate.getTime());//Create the timestamp from the above date object.
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
                    PreparedStatement ps = objConn.prepareStatement(insertStatement);
                    ps.setString(1, userid);
                    ps.setString(2, ipaddress);
                    ps.setTimestamp(3, ts);
                    ps.setString(4, page);
                    ps.setString(5, filename);
                    ps.executeUpdate();
                    objConn.commit();
                    ps.close();
                    objConn.close();
                    System.out.println("recordusage method called");
                catch (SQLException s)
                    System.err.println("DataBase PROBLEM");
                    s.printStackTrace();
                catch (Exception e)
                        System.err.println("Error in recordUsage method");
                        e.printStackTrace();
    }Here is the error generated:(I hate to dump this on you)
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    root cause
    javax.servlet.ServletException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
         at org.apache.jsp.download_jsp._jspService(download_jsp.java:93)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
         at java.lang.Thread.run(Thread.java:534)
    TIA!!

    And what makes you think that the above code is causing the problem?

  • Prepared Statement help -- cant get it to work :(

    Context initialcontext = new InitialContext();
              DataSource datasource = (DataSource)initialcontext.lookup("java:comp/env/XYZ");
              Connection conn = datasource.getConnection();                
              String UPDATE = "update query with ?s ";
              PreparedStatement pstmt = conn.prepareStatement(UPDATE);
              pstmt.setString(1,title);
              pstmt.setString(2,desc);
              pstmt.setInt(3,1);
              System.out.println("2a");
              pstmt.executeQuery(); ------- STUCK HERE
              System.out.println("2b");                              
              pstmt.close();
    It goes between 2a and 2b and just stops working.. no errors nothing...
    I have been trying to get this working the entire day... with no luck... any suggestions........

    I am familiar with a few dialects of SQL. I've never seen
    UPDATE <tbl> WITH...
    What RDBMS are you using? I just searched the mySQL documentation on the keyword WITH (case sensitive) and found no form of update that uses it.
    The ANSI SQL UPDATE statement takes the form...
    UPDATE <tbl> SET <col> = <value>[, <col> = <value>...]
    Also, you have three calls to setString, but only one ? in your String UPDATE indicating a position for a parameter.
    http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
    Hope this helps. If there is a form of UPDATE that uses WITH, please provide me with a reference link. I'm supposed to know SQL. :-)

  • Prepared Statement - Help pl

    Hi!
    Is there any disadvantage in using a Prepared statement to insert records in to the database.What is the difference in using Prepared Statement compared to Statement.Any disadavantage?I know the advantage of using Prepared statement where by I can insert values with special characters.Any disadavantage of using Prepared statement regularly?Please explain.Thanks

    hello all, i like the statement that some of u guys posting here..
    i have a puzzle here, if i have more than one query to table, lets say 3rd query are depends on result of 2nd query which taken from 1st query result.
    should i use prepared statement instead of statement? can we say that using of prepared statement can make our query result faster than using statement??
    i have a function here which goes well when using statement st,
    public void getMainlevelBcat(String loggedbizid){
    String query = " SELECT DISTINCT category2.mainlevel FROM bizcategory2, category2 "+
    " WHERE bizcategory2.catid = category2.catid "+
    " AND bizcategory2.bizid ='"+loggedbizid+"' ";
    try {
    st = con.createStatement();
    rs =st.executeQuery(query);
    catch (SQLException e) {
    System.out.println(e.getMessage());
    can anybody chance it to new function using prepared statement??

  • Prepared statement help... pls...

    hey all... need help... this prepared statement is driving me mad... keeps throwing an error in my servlet.... can somebody pls help
         PreparedStatement updateWiki = con.prepareStatement("UPDATE sportinfo SET pageinfo,parent = (?,?) WHERE sport LIKE ? ");
              updateWiki.setString(1, wikipage);
              updateWiki.setString(2, parent);
              updateWiki.setString(3, sport);
              updateWiki.executeUpdate();
    am i missing something???
    thanks keith

    1. What is the error? Please post it.
    2. Try using the query like:
    UPDATE sportinfo SET pageinfo=?,parent=? WHERE sport LIKE ?
    and see if it still fails.

Maybe you are looking for