Handling exceptions problem

for my class we have to throw an exception if the user inputs any characters into a text field (its for converting fahrenheit to celsius). anyway, here is the part of my code that does this:
String input = "";
double temp;
boolean test = true;
//try statement
try
     input = fahr.getText();
//catch statement
catch (NumberFormatException f)
     JOptionPane.showMessageDialog(null, "Invalid data was entered, try again.");
     test = false;
if (test)
     //convert to celsius
     temp = (Double.parseDouble(input) - 32) / 1.8;
     //display result
     JOptionPane.showMessageDialog(null, input + " degrees Fahrenheit is "
                         + temp + " degrees Celsius.");
}i thought it would catch the exception, but this is what i get when i input a letter into the text field (it comes up in the dos prompt):
java.lang.NumberFormatException: For input string: "y"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
        at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1
207)
        at java.lang.Double.parseDouble(Double.java:220)
        at TemperatureWindowR$CalcButtonListener.actionPerformed(TemperatureWind
owR.java:96)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
86)
        at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
ctButton.java:1839)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
istener.java:245)
        at java.awt.Component.processMouseEvent(Component.java:5100)
        at java.awt.Component.processEvent(Component.java:4897)
        at java.awt.Container.processEvent(Container.java:1569)
        at java.awt.Component.dispatchEventImpl(Component.java:3615)
        at java.awt.Container.dispatchEventImpl(Container.java:1627)
        at java.awt.Component.dispatchEvent(Component.java:3477)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
        at java.awt.Container.dispatchEventImpl(Container.java:1613)
        at java.awt.Window.dispatchEventImpl(Window.java:1606)
        at java.awt.Component.dispatchEvent(Component.java:3477)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:201)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:151)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

I only glanced at your code, but it looks like you have most of the right pieces, just in the wrong places a little bit. Roughly like this: boolean accepted = false;
while (!accepted) { // need to keep looping until they get it right.
    try {
        read user input
        // This needs to be inside the try, since it  throws the exception we want to catch
        temp = Double.parseDouble(...) etc.
        // If we got this far, then the above didn't throw, so it's a number
        accepted = true;
    catch (NumberFormatException exc) {
        // since we didn't get far enought to set accepted to true, we'll go through the loop again
        "Try again" message
process temp

Similar Messages

  • Problem with  Handling  Exception  in Jsp

    hi
    I am unable to handling exception in Jsp.
    In my Simple Form i taken a simple text field named salary.
    Details.jsp
    <%@ page language="java" isErrorPage="true" errorPage="Det.jsp"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <html:html>
    <html:form action="/det.do">
    Enter Salary<html:text property="sal"/><br>
    <br>
    <html:submit value="SEND" />
    </html:form>
    </html:html>and my Actionclass is:
    package com.gurukul.util;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class DetUserAction extends Action {
         String s=null;
         int sal;
    public ActionForward execute(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
         try
         sal=Integer.parseInt(req.getParameter("sal"));
         if (sal>0)
              s="success";
         else
         throw new SalException(sal);}
         catch(SalException e)
              e.getMessage();
         return map.findForward(s);
    and my Formbean is
    package com.gurukul.util;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class DetUserAction extends Action {
         String s=null;
         int sal;
    public ActionForward execute(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
         try
         sal=Integer.parseInt(req.getParameter("sal"));
         if (sal>0)
              s="success";
         else
         throw new SalException(sal);}
         catch(SalException e)
              e.getMessage();
         return map.findForward(s);
    }and my struts-config.xml is
                                  </form-bean>
                                  <form-bean name="DetUser"  
                           type="com.gurukul.util.DetUserForm">
                                  </form-bean>
    <action path="/det"
                          type="com.gurukul.util.DetUserAction"
                          name="DetUser"
                        input="/Details.jsp"
                           scope="request">
                           <exception key="errors.sal"
                           type="com.gurukul.util.SalException"
                           path="/jsp/Det.jsp"/>
                       <forward name="success" path="/jsp/DetailList.jsp"  />
                       <forward name="failure" path="/jsp/Details.jsp"/>
                         </action>and Det.jsp(i.e error jsp) is
    <%@ page language="java" isErrorPage="true"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <html:html>
    <center><b>
    Invalid Salary</b></center>
    <%= exception.getMessage() %>
    </html:html>but i didnt get exception on jsp.
    please help me
    Regards
    VAS

    hi
    can you please guide me how to handle exceptions in Jsp(struts)?

  • Invalid Handle Exception-What is the reason?

    I face with "Invalid Handle exception" (SQLException) while using the following code.
    Could anybody tell me the possible reasons/Situation the error rise?
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(SQLStmt);
         if(rs!=null){
    ResultSetMetaData rsm = rs.getMetaData();
         int totalcols = rsm.getColumnCount();
         Vector temp;
         while (rs.next()) {
         Vector temp = new Vector();
         for (int i = 1; i <= totalcols; i++) {
              String value = rs.getString(i);
              if (value == null) {
              value = "";
         temp.addElement(value);
         }//for loop ends here
         valueVector.addElement(temp);
         rs.close();
         stmt.close();     
    Thank you all

    Vector temp;
    while (rs.next()) {
    Vector temp = new Vector();Are you sure that this is the code you are running? The reason I ask is that I'm pretty sure that it won't compile, at least under JDK1.4. You should get a compile error something like "temp is already defined".
    If thats not the problem you need to find out on which line the error actually occurs. You can get this from the exception by calling the printStackTrace() method.
    Col

  • How to handle exceptions in a Service

    Hi,
    I'm trying to get the new Service (background thread) stuff working and am close but I have a problem with handling exceptions that are thrown in my Task. Below is my code, does anyone know if I am doing something wrong, or is this just a flaw in the system at the moment:
    Here is my service:
    public class TestService extends Service<String>
        protected Task<String> createTask()
            return new Task<String>()
                protected String call() throws Exception
                   System.out.println("About to throw exception from inside task");
                   throw new Exception("Test failure");
    }Here is my code using this service:
    public void doTest()
        final TestService test = new TestService();
        test.stateProperty().addListener(new ChangeListener<Worker.State>()
            public void changed(ObservableValue<? extends Worker.State> source, Worker.State oldValue, Worker.State newValue)
                System.out.println("State changed from " + oldValue + " to " + newValue);
        test.start();
    }When the task throws its exception I was hoping to get a state change to FAILED but the callback is never triggered. I've tried listening for invalidation of the state and also tried listening to all the other properties on Service (running, progress, exception, etc). There doesn't seem to be any feedback after the exception has been thrown.
    Am I using this wrong, or is it a bug?
    Cheers for you help,
    zonski

    Hi,
    This was working in the build #32. I updated the JavaFX to build #36 and it stopped working.
    I checked in the latest build #37 as well which was released last week and this doesn't work here as well.
    If the task is succeeding the state is getting changed to SUCCEEDED but in case of an exception there is no change in the state
    Edited by: user12995677 on Aug 3, 2011 2:07 AM

  • How can I handle exception? - to give user more friendly notification

    Hi!
    User gets an error:
    'Error in mru internal routine: ORA-20001: Error in MRU: row= 1, ORA-20001: ORA-20001: Current version of data in database has changed since user initiated update process. current checksum =...'
    How can I handle this exception (when two users want to modify the same set of data at the same time)? I would like to hide the above error message and give user more friendly notification.
    Thanks in advance,
    Tom

    Thanks Vikas for your answer.
    These workarounds are really creative and I want to use one of them. BUT my problem is to 'catch' the exception/error when two users want to modify the same set of data at the same time.
    Those solutions which we can read about in this link you gave me describe handling exceptions in pl/sql processes. How can I catch the error I am talking about in pl/sql code?
    Code would be like this:
    DECLARE
    two_users EXCEPTION;
    BEGIN
    IF --catch the error
    THEN RAISE two_users;
    END IF;
    EXCEPTION WHEN two_users
    THEN :HIDDEN_ITEM := 'Error Message';
    END;
    What should I put in a place where there is '--catch the error' ??
    Thanks in advance,
    Tom

  • Handling exceptions inside a Presentation

    Hi people, I have a problem handling exceptions inside a Presentation that it is inside an screenflow (that it is inside a Global Creation Activity). This it is in some way related to this other thread: Managing transactions with DynamicSQL
    I have an Interactive Activity that renders an Object BPM's Presentation. This Presentation has dependent combos (i.e.: Country, State, City).
    Although I can add an exception transition to the Interactive Activity, if the BP-Method that fills the other combo fails, this exception transition it is not executed. Instead, it shows a screen with the stack trace.
    The solution I've found: catch the exception inside the BP-Method, and use this.showError let the user know that something went wrong.
    This solves my problem, but I'd like to know why ALBPM let me put an exception transition from an Interactive Activity? I mean, in which cases this transition could be executed
    Thanks in advance!

    This does not solve my problem, but I think that it would be a better design idea not to allow presentations to call server-side BP-Methods directly. Instead it should call a client-side BP-Method and from this method call the one in the server.
    This should improve the way we can handle an error that occurs on a server-side BP-Method
    It's for sure a "best practice", but I think it would be better if the tool help us to implemented this way
    What do you think?

  • Handle Exceptions during the Render Response phase

    Hi,
    How can we handle exceptions that occur during the render response phase, e.g. to redirect the user to an error page?
    In our application we have an unbounded taskflow with one page (jspx). It's quite a simple page, as it only displays some data from a managed bean.
    When we run the application and e.g. throw explicitly a RuntimeException form one of the getters, all we get is the 'progress indicator', not even a stacktrace on the page (only in the logs).
    Unfortunately, it doesn't seem possible to handle the exception, not via the taskflow Exception Handler, the web.xml error-page or a custom ADF Controller exception handler. In the latter case, we can catch the exception but when we try a redirect (on the external context or response) we get a 'java.lang.IllegalStateException: Response already committed' exception.
    Any suggestions?
    Ciao
    Aino

    Hi Aino
    I'm not sure if that's the problem, but I recently read somewhere (wish I remember where) an IllegalStatementException that was throwing because there was no entry page defined in web.xml.
    If you are trying that, remember that web.xml doesn't support .jspx pages.
    Edited by: TheCrusader on 09-jul-2010 15:03
    Edited by: TheCrusader on 09-jul-2010 15:10

  • What is the best way to handle Exception in Java?

    We are designing an application that will be developed using JSP + EJB .
    To deal with the exception part, we have thought about following solutions
    (1)All methods in EJB will be declare with throws clause, with the respect to the potential exceptions that can be thrown by method.
    We will catch only those exceptions, for which we can take alternative steps or further action when they occurred. All other exceptions will be thrown to the caller.
    (2)All JSP pages will have try/catch that catches exceptions thrown by EJB or by JSP code.
    (3)A common JSP file will be designated to handle Exception by setting isErrorPage property true and all JSP files are pointing to that particular file for exception handling.
    (4)Whenever any exception occurred in application, it will bubbled up and end user will get a common JSP page designed to handle exception.
    I am looking for the suggestions to improve this mechanism.
    Regards,
    Chetan

    The problem with the standard expection handling in a web environment is that all the potentially useful status information goes to the user, who probably won't make head nor tail of it. It also goes to the logs which someone might, or might not get arround to reading.
    What I do is to have a standard method called to deal with unanticipated exceptions and e-mail me a status report. This contains not just the extended stack trace (chasing any level of wrapped exception) but also details of the transaction being processed, including the user if known.
    Set up an e-mail alias with a list of people to receive these reports. Often you can have the problem fixed, and send the user an apologetic e-mail before they even get a complaint in.
    Create JSP tags to do this with any other per-page housekeeping.

  • Handle Exception from LCDS

    Hello,
    I am using Flex 4 with LCDS 3. I am having problems with properly handling 
    exceptions. 
    I have a simple commit service like; 
    var commitToken:AsyncToken = 
    _serviceName.serviceControl.commit(); // Commit the change. 
    commitToken.addResponder(new AsyncResponder( 
    function (event:ResultEvent, 
    token:Object=null):void 
    Alert.show("DATA DELETED"); 
    function (event:FaultEvent, 
    token:Object=null):void 
    Alert.show("Save failed: " + 
    event.fault.faultString, "Error"); 
    _serviceName.serviceControl.revertChanges(); 
    Now when I try to delete a row which has a child record I get the following 
    error in my tomcat log; 
    hdr(DSEndpoint) = my-rtmp 
    hdr(DSId) = 9AFF219A-AB2A-3B60-D990-9E87A3D7CF71 
    java.lang.RuntimeException: Hibernate jdbc exception on operation=deleteItem 
    error=Could not execute JDBC batch update : sqlError = from SQLException: 
    java.sql.BatchUpdateException: ORA-02292: integrity constraint (CATEGORY_FK) 
    violated - child record found 
    followed by; 
    [LCDS]Serializing AMF/RTMP response 
    Version: 3 
    (Command method=_error (0) trxId=10.0) 
    (Typed Object #0 'flex.messaging.messages.ErrorMessage') 
    rootCause = (Typed Object #1 'org.omg.CORBA.BAD_INV_ORDER') 
    minor = 0 
    localizedMessage = "The Servant has not been associated with an ORB 
    instance" 
    message = "The Servant has not been associated with an ORB instance" 
    cause = null 
    completed = (Typed Object #2 'org.omg.CORBA.CompletionStatus') 
    destination = "CATEGORY" 
    headers = (Object #3) 
    correlationId = "D4B6573F-F8C2-0732-BD1C-6FD1C5979763" 
    faultString = "Error occurred completing a transaction" 
    messageId = "9AFF6D9A-3C1C-E99B-B00F-92E72069B64E" 
    faultCode = "Server.Processing" 
    timeToLive = 0.0 
    extendedData = null 
    faultDetail = null 
    clientId = "C2F15FE1-2977-23AA-1ADD-6FD1C096A82F" 
    timestamp = 1.281776280572E12 
    body = null 
    In flex in my "event" in the fault function I can only get general data like 
    "Error occurred completing a transaction", but I cannot access the error 
    "ORA-02292:...". 
    Is there a way to access it, as I need to handle multiple exceptions that Oracle 
    will catch such as duplicate ID.....

    Hi Hong,
    I can confirm that 0xE8010014 represents a driver fault. Unfortunately without a dump or some other trace file it is hard to track this down. You could create a dump file if you can reproduce it, upload it to your OneDrive and then post the link here, I
    can grab it and take a look.
    >>This is reported by users. Unfortunately I am unable to reproduce it.
    Could you please collect the OS version which have this issue?
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to handle exceptions / errors in LiveCycle

    Hello All ,
    I want to handle some exception / errors that may arise while the user is filling the form so that the JavaScript console should not show any error rather we can simply show an alert / message .
    Say I got a dynamic table where the user can add / delete row at run time . There is a minimum count for the no.of rows . Suppose the user clicks the delete button without adding a new row then the JavaScript console will show error . I know we can handle this by using if else statements where depending on the instance manager count the deletion of rows are permitted . I want to know is it possible here to write a code to handle exception considering this thing as an exception without using the If-else statement ?? Just a thought.
    Thanks.
    Bibhu.

    What you're looking for is the javascript:
    try{
    // code
    } catch (err) {
    // fail code
    However, this is not the right way to solve your problem: Exception handling is for handling exceptions, and a scenario that you know can come to pass (such as the user clicking the removeInstance button when there are none to remove) is not an exception.
    Don't misunderstand me - putting code inside try/catch is 'good developer manners' (I do it myself all the time), and I strongly encourage you to do the same. Although only for handling exception sprung from code that you think should work just as fine without them.
    A better way of solving your particular problem is to remove the minus-button if there are no instances to remove.

  • Conflict Error Handler Exception in  Cluster

              Hi
              We bind some objects using rebind method to the JNDI in our weblogic servers.
              If we run one instance of weblogic server no problem but if we start another one
              server in the cluster it throughs conflict error handler exception. More over
              if we refresh one object instance in one server (by rebind) the new changes in
              the object doesn't reflect in other servers.
              

    If you bind non clusterable objects in the jndi from two servers then you
              will run into conflicts.
              Basically in a cluster, two servers cannot provide the same service unless
              it is clusterable.
              WLS assumes that everything you bind into jndi is a service.
              -- Prasad
              "BSIL" <[email protected]> wrote in message
              news:3b94f93a$[email protected]..
              >
              > Hi
              > We bind some objects using rebind method to the JNDI in our weblogic
              servers.
              > If we run one instance of weblogic server no problem but if we start
              another one
              > server in the cluster it throughs conflict error handler exception. More
              over
              > if we refresh one object instance in one server (by rebind) the new
              changes in
              > the object doesn't reflect in other servers.
              

  • Additional uncaught exception thrown while handling exception.

    Hello all! I am *trying* to surf around the internet and do a little online shopping. I keep getting this error though and it is really bugging me/ruining my night. I am about ready to through my computer at a wall.
    Here is the error:
    Additional uncaught exception thrown while handling exception.
    Here is the full error as it appears on my screen:
    Additional uncaught exception thrown while handling exception.
    Original
    RedisException: Redis server went away in Redis->setOption() (line 23 of /home/www/usa.hunter-boot.com/htdocs/drupalroot/sites/all/modules/contrib/redis /lib/Redis/Client/PhpRedis.php).
    Additional
    RedisException: Redis server went away in Redis->setOption() (line 23 of /home/www/usa.hunter-boot.com/htdocs/drupalroot/sites/all/modules/contrib/redis /lib/Redis/Client/PhpRedis.php).
    It is REALLY bugging me. I don't know that much about computers other then the basics. I only use mine to write papers and go on the internet so if someone is nice enough to try and help me fix this issue then please don't use fancy tech lingo (dumb it down for me). Thank you!

    That's a problem on the web server, not on your computer.

  • OWB Mapping handle Exception

    Hi folks,
    Is There a way to handle exeption of a OWB 11r2 mapping in SQLPLUS shell?
    I need run few mapping in sqlplus script, but I need that if the mapping faild for any reason mapping must handle exceptoin, and exit from sqlplus.
    Now if a mapping faild, it dosen't handle exception and the next mapping start..... this is a problem for me...
    thanks
    Emilio

    Hi Thomas,
    thanks for reply, but I just do it...... but this workaround it's not very good for me.......
    I wrote this script:
    qlplus -s $1 << EOF
    VARIABLE p_status VARCHAR2(100);
    whenever sqlerror exit 1;
    ALTER SESSION SET NLS_NUMERIC_CHARACTERS = '. ' ;
    set timing on;
    declare
    begin
    MAP_FACT_INTERVENTO.MAIN(:p_status);
    if :p_status <> 'OK' then
    raise INVALID_NUMBER;
    end if;
    MAP_FACT_INTERVENTO_P2.MAIN(:p_status);
    if :p_status <> 'OK' then
    raise INVALID_NUMBER;
    end if;
    I raise a generec INVALID_NUMBER exception when p_status is <> 'OK', Is there a way to raise the real exception!?!?
    thanks
    Emilio

  • Can we handle exceptions for the expressions in select query?

    Hi all,
    Can we handle exceptions for the expressions in select query.
    I created a view, there I am extracting a substring from a character data and expected that as a number.
    For example consider the following query.
    SQL> select to_number( substr('r01',2,2) ) from dual;
    TO_NUMBER(SUBSTR('R01',2,2))
    1
    Here we got the value as "1".
    Consider the following query.
    SQL> select to_number( substr('rr1',2,2) ) from dual;
    select to_number( substr('rr1',2,2) ) from dual
    ORA-01722: invalid number
    For this I got error. Because the substr returns "r1" which is expected to be as number. So it returns "Invalid number".
    So, without using procedures or functions can we handle these type of exceptions?
    I am using Oracle 10 G.
    Thanks in advance.
    Thank you,
    Regards,
    Gowtham Sen.

    SQL> select decode(ltrim(rtrim(translate(substr('r21', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('r21', 2, 2)), null) from dual;
    DE
    21
    SQL> ed a
    SQL> select decode(ltrim(rtrim(translate(substr('rr1', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('rr1', 2, 2)), null) from dual;
    D
    -

  • How to handle exceptions of rfc in web dydnpro

    hi all,
    i want to handle exceptions of Remote function module in webdynpro.how can we do that one.are there any variables in model class for those exceptions.
    regards
    Naidu

    Hi,
    Hope the following snippet answers ur query
    IWDMessageManager manager = wdComponentAPI.getMessageManager();
                   try{
                        wdContext.currentB_Quotation_Createfromdata_InpElement().modelObject().execute();
                        wdContext.nodeOutputQuotation().invalidate();
                   } catch(WDDynamicRFCExecuteException ce) {
                        manager.reportException(ce.getMessage(), false);

Maybe you are looking for

  • Problem in automatically clear open items on  FIFO basis

    Hi all    My requirement is like that I want to automatically clear open items on  FIFO basis with only one condition on Customer Code should be match. Is there is standard program or BAPI for that except sapf124(f.13).  Or I have to write a new prog

  • OSB - Problem using the Service Callout control in a proxy service

    Greetings, Using a Service Callout control in a proxy service requires to check one of the following two options: Configure SOAP Body or Configure Payload Document. Both require to write SOAP code and to assign it to variables that will be used in th

  • Converting seconds value to a date

    Hi, I have date column as integer like 1212638737.Could anyone tell me the way of converting this value to corresponding date value?

  • RAW file into jpg image

    I am exploring the wonderful world of RAW photography processing. I have come across an issue that I cannot find an answer to. After doing all the image adjustments, how do I save it as a jpg file? The only option I see is to save it as a dng file or

  • Looking for transaction code in MM to display Business Area, PO, AO,& Values

    Hello everyone, I am looking for a Transaction Code that will display Business Area, Outline Agreement, Purchase Order and Values. Can anyone recommend? Ananh