Handling Consecutive NumberFormat Exceptions

I have written a Binary Search Program for which I am asking the user to enter the size and the elements of the array.
If the user enters the size say 5
Now he can enter up to a max of 5 max numbers to populate the array.
If the user enters an alphabet it should not be accepted and it would throw an exception and its caught properly for the first time and the user is asked to enter the number again. Now again if the user enters an alphabet my program is not robust enuf to throw an error to the user and continue the user to enter a number from that point. How do i handle such exceptional conditions.
import java.util.Arrays;
import javax.swing.JOptionPane;
public class BinarySearch {
     public static void main(String[] args) {
          String n = JOptionPane.showInputDialog(null, "Enter the size of the array");
          int size = Integer.parseInt(n);
          int a[] = new int[size];
          int i = 0;
          while(i < size){
               String arrayn = JOptionPane.showInputDialog(null, "Enter the "+(i+1)+" th element of the array");
               try{
                    a[i] = Integer.parseInt(arrayn);
               }catch (Exception e){
                    arrayn = JOptionPane.showInputDialog(null, "Enter the "+(i+1)+" th element of the array");
                    a[i] = Integer.parseInt(arrayn);
               i++;
          System.out.print("The elements of the array are : ");
          for(int j = 0; j < size; j++){
               System.out.print(a[j]+"  ");     
          Arrays.sort(a);               //Sorting the numbers for Binary Search
          System.out.println();
          System.out.print("The Sorted elements of the array are : ");
          for(int j = 0; j < a.length; j++){
               System.out.print(a[j]+"  ");     
          String key = JOptionPane.showInputDialog(null, "Enter the element to search for from the array");
          int searchKey = Integer.parseInt(key);
          int position = binarySearch(a, searchKey);
          System.out.println();
          if(position == -1){
               System.out.println("The element could not be found");
          }else{
               System.out.println("The element found at "+position+"th position of the array");
     public static int binarySearch(int a[], int searchKey){
          int low, high, middle;
          int index = -1;
          low = 0;
          high = a.length - 1;
          middle = (low + high + 1) / 2;
          do{
               if(searchKey == a[middle]){
                    return middle;
               }else if(searchKey < a[middle]){
                    high = middle -1;
               }else{
                    low = middle + 1;
               middle = (low + high + 1) / 2;
          }while(low <=high && (index == -1));
          return index;
}Message was edited by:
hemanthjava

Hi,
I made the changes. I am getting NumberFormat Error for the size even after making a change.
int k = 0;
          while(k < 1){
               try{
                    n = JOptionPane.showInputDialog(null, "Enter the size of the array");
                    k++;
               }catch (Exception e) {
                    System.out.println("Please enter a number for size");
                    continue;
Exception in thread "main" java.lang.NumberFormatException: For input string: "j"
     at java.lang.NumberFormatException.forInputString(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at BinarySearch.main(BinarySearch.java:19)
Message was edited by:
hemanthjava

Similar Messages

  • How to Handle RFC delivery exception (rfcClientException) in XI?

    I have a following scenario.
    I have an outbound soap interface (sender) and inbound RFC(receiver). When the soap message is posted it goes to receiver where it has to execute the RFC. It tries to convert the XML to RFC and throws the following exception.
    com.sap.aii.af.ra.ms.api.DeliveryException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: could not convert request from XML to RFC:com.sap.mw.jco.JCO$ConversionException: (122) JCO_ERROR_CONVERSION: Date 'xxxx-xx-xx' has a wrong format at field CREAT_DATE: Unparseable date: "xxxx-xx-xx
    I defined the fault message and attached it to the Inbound Interface. I also defined the mapping of receiver exception message to fault message. I am expecting a fault message back to sender which is not happening.
    When I go to moni and try to look for the error in the response message I see the following.
    <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
    <SAP:Category>XIAdapterFramework</SAP:Category>
    <SAP:Code area="PARSING">GENERAL</SAP:Code>
    <SAP:P1 />
    <SAP:P2 />
    <SAP:P3 />
    <SAP:P4 />
    <SAP:AdditionalText>com.sap.aii.af.ra.ms.api.DeliveryException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: could not convert request from XML to RFC:com.sap.mw.jco.JCO$ConversionException: (122) JCO_ERROR_CONVERSION: Date 'xxxx-xx-xx' has a wrong format at field CREAT_DATE: Unparseable date: "xxxx-xx-xx"</SAP:AdditionalText>
    <SAP:ApplicationFaultMessage namespace="" />
    <SAP:Stack />
    <SAP:Retry>M</SAP:Retry>
    </SAP:Error>
    I am suspecting that since the fault message does not contain this structure it's not able to build it.
    How do I handle such runtime exception and transfer it to sender system. Any help would be greatly apperciated.

    I have the same problem. The error is as follows:
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    - <!--  Call Adapter
      -->
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
      <SAP:Category>XIAdapterFramework</SAP:Category>
      <SAP:Code area="PARSING">GENERAL</SAP:Code>
      <SAP:P1 />
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText>com.sap.aii.af.ra.ms.api.DeliveryException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: could not convert request from XML to RFC:com.sap.mw.jco.JCO$ConversionException: (122) JCO_ERROR_CONVERSION: Date '2006/04/09' has a wrong format at field INVALIDITYBEGIN: Unparseable date: "2006/04/09"</SAP:AdditionalText>
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack />
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Anyone have any idea, how should I resolve the data format issue?
    Thanks

  • How to handle multiple save exceptions (Bulk Collect)

    Hi
    How to handle Multiple Save exceptions? Is it possible to rollback to first deletion(of child table) took place in the procedure.
    There are 3 tables
    txn_header_interface(Grand Parent)
    orders(parent)
    order_items (Child)
    One transaction can have one or multiple orders in it.
    and one orders can have one or multiple order_items in it.
    We need to delete the data from child table first then its parent and then from the grand parent table.if some error occurs anywhere I need to rollback to child record deletion. Since there is flag in child table which tells us when to delete data from database.
    Is it possible to give name to Save exceptions?
    e.g.
    FORALL i IN ABC.FIRST..ABC.LAST SAVE EXCEPTIONS A
    FORALL i IN abc.FIRST..ABC.LAST SAVE EXCEPTIONS B
    if some error occurs then
    ROLLBACK A; OR ROLLBACK B;
    Please find the procedure attached
    How to handle the errors with Save exception and rollback upto child table deletion.
    CREATE OR REPLACE
    PROCEDURE DELETE_CONFIRMED_DATA IS
    TYPE TXN_HDR_INFC_ID IS TABLE OF TXN_HEADER_INTERFACE.ID%TYPE;
    TXN_HDR_INFC_ID_ARRAY TXN_HDR_INFC_ID;
    ERROR_COUNT NUMBER;
    BULK_ERRORS EXCEPTION;
    PRAGMA exception_init(bulk_errors, -24381);
    BEGIN
    SELECT THI.ID BULK COLLECT
    INTO TXN_HDR_INFC_ID_ARRAY
    FROM TXN_HEADER_INTERFACE THI,ORDERS OS,ORDER_ITEMS OI
    WHERE THI.ID = OS.TXN_HDR_INFC_ID
    AND OS.ID = OI.ORDERS_ID
    AND OI.POSTING_ITEM_ID = VPI.ID
    OI.DW_STATUS_FLAG =4 --data is moved to Datawarehouse
    MINUS
    (SELECT THI.ID FROM TXN_HEADER_INTERFACE THI,ORDERS OS,ORDER_ITEMS OI
    WHERE THI.ID = OS.TXN_HDR_INFC_ID
    AND OS.ID = OI.ORDERS_ID
    OI.DW_STATUS_FLAG !=4);
    IF SQL%NOTFOUND
    THEN
    EXIT;
    END IF;
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM ORDER_ITEMS OI
    WHERE OI.ID IN (SELECT OI.ID FROM ORDER_ITEMS OI,ORDERS
    OS,TXN_HEADER_INTERFACE THI
    WHERE OS.ID = OI.ORDERS_ID
    AND OS.TXN_HDR_INFC_ID = THI.ID
    AND THI.ID = TXN_HDR_INFC_ID_ARRAY(i));
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM ORDERS OS
    WHERE OS.ID IN (SELECT OS.ID FROM ORDERS OS,TXN_HEADER_INTERFACE THI
    WHERE OS.TXN_HDR_INFC_ID = THI.ID
    AND THI.ID = TXN_HDR_INFC_ID_ARRAY(i));
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM TXN_HEADER_INTERFACE THI
    WHERE THI.ID = TXN_HDR_INFC_ID_ARRAY(i);
    COMMIT;
    DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, 'DD-MON-YY HH:MIPM')||':
    DELETE_CONFIRMED_DATA: INFO:DELETION SUCCESSFUL');
    EXCEPTION
    WHEN OTHERS THEN
    ERROR_COUNT := SQL%BULK_EXCEPTIONS.COUNT;
    DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, 'DD-MON-YY HH:MIPM')||':
    DELETE_CONFIRMED_DATA: ERROR:Number of errors is ' ||ERROR_COUNT);
    FOR indx IN 1..ERROR_COUNT LOOP
    DBMS_OUTPUT.PUT_LINE('Error ' || indx || 'occurred during
    '||'iteration'||SQL%BULK_EXCEPTIONS(indx).ERROR_INDEX);
    DBMS_OUTPUT.PUT_LINE('Error is '
    ||SQLERRM(-SQL%BULK_EXCEPTIONS(indx).ERROR_CODE));
    END LOOP;
    END DELETE_CONFIRMED_DATA;
    Any suggestion would be of great help.
    Thanks in advance
    Anu

    If you have one or two places in your code that need multiple exceptions, just do it with multiple catch statements. Unless you are trying to write the most compact Programming 101 homework program, inventing tricks to remove two lines of code is not good use of your time.
    If you have multiple catches all over your code it could be a code smell. You may have too much stuff happening inside one try statement. It becomes hard to know what method call throws one of those exceptions, and you end up handling an exception from some else piece of code than what you intended. E.g. you mention NumberFormatException -- only process one user input inside that try/catch so it is easy to see what error message is given if that particular input is gunk. The next step of processing goes inside its own try/catch.
    In my case, the ArrayIndexOutOfBoundsException and
    NumberFormatException should be handled by the same way.Why?
    I don't think I have ever seen an ArrayIndexOutOfBoundsException that didn't indicate a bug in the code. Instead of an AIOOBE perhaps there should be an if statement somewhere that prevents it, or the algorithm logic should prevent it automatically.

  • How can we handle user defined exceptions in ejbStore() of entity bean

    Accroding to my knowledge in ejbStore we can not handle user defined exceptions. Can anybody help on this????

    In my case I am calling a method from ejbsotre() . In that method i wanted to put some checks according to that i wanted to throw exceptions.
    In this case how would I handle exceptions.
    Can you suggest in this case,please !!!

  • Extend BizTalk ESB Exception Handling to manage exception for all organization wide application exception

    Hello,
    Can we Extend BizTalk ESB Exception Handling to manage exception for all organization wide application ( both biztalk and external) exception ?
    Is it something a good option or there are better approach to do this.
    Business requirement is Exception management should be single window for complete end-to end application ( source-Biztalk - destination)
    Tarun
    Tarun

    Hi Tarun,
    ESB Toolkit framework for exception handling is not complete OOTB. it is intended as a framework and set of patterns that can and should
    be extended based on the customer’s needs.
    One way of extending the capabilities is by using Standardized Exception Management or SEM in short. 
    SEM solution extends the capabilities of the Microsoft ESB Exception Management Framework and follows a design pattern that provides a flexible
    approach to exception monitoring and enables error responses to originate from outside of the solution. While SEM is primarily targeted to Microsoft BizTalk Server applications, it can also be leveraged by other applications that are able to call a Windows
    Communications Foundation (WCF) or web service.
    Refer: Standardized Exception Management
    Standardized Exception Management (SEM)
    Rachit

  • Error handle request; Root exception is: java.lang.NoSuchMethodError

    Hello Guys,
    I am running EBS 11i, rdbms 10g on OEL4. After applying a bunch of patches to resolve some IE issues I ran into an error:
    "FRM-41072: Cannot create group ACTION_REC_GROUP" when trying to cancel a PO.
    An SR directed me to apply patch 8286920 which indeed fixed the FRM-41072 error. After this patch "Logon to Oracle Applications Manager" is not possible as the page gives me :
    Error handle request; Root exception is: java.lang.NoSuchMethodError: oracle.apps.fnd.security.AolSecurity.userPwdHash(Ljava/lang/String;)Ljava/lang/String;
    MOS thinks that patch 8286920 didn't break OAM but I don't think so since this is only happening on my DEV and TEST systems on which I have applied the patch. PROD, wihtout the patch, is accessible through OAM just as usual?
    Any thouths?
    Thank you
    Mathias

    Did you apply all patches mentioned in the following docs?
    FRM-41072 - Unable to Cancel Purchase Order or Purchase Order Line or Release [ID 947402.1]
    Change Tax Code in the Purchase Order Gets Error - Could not reserve record (2 tries) Keep trying [ID 956047.1]
    Autocreate Process Does Not Default Purchase Order Form As The Active Window After PO Is Created - Does Not Come To The Front [ID 1055623.1]
    Did you bounce all the services and see if you ca reproduce the issue?
    What about clearing the server cache files? -- How To Clear Caches (Apache/iAS, Cabo, Modplsql, Browser, Jinitiator, Java, Portal, WebADI) for E-Business Suite? [ID 742107.1]
    Can you find any errors in the database/apache log files? Any invalid objects?
    If you have verified all the above please update the SR with the error you have after applying that patch.
    Thanks,
    Hussein

  • How to handle user defined exception from C#?

    Hi:
    I have some PL/SQL code that will throw a user defined exception if certain conditions are met. How do I handle user defined exceptions if this procedure/function is being called from C#? C# can handle a normal Oracle SQL error (e.g. ORA-XXXX) because they are defined in the proper class, but how do I get it to know about my user defined exception? Does anyone have any links to examples of doing this?
    Thanks.

    Hi Gaff,
    Is there a particular problem you're having doing this? It works as normal for me...
    Cheers
    Greg
    PLSQL
    =========
    create or replace procedure throwsomething as
    begin
    raise_application_error(-20001,'kaboom');
    end;
    ODP
    =====
        class Program
            static void Main(string[] args)
                using (OracleConnection con = new OracleConnection())
                    con.ConnectionString = "user id=scott;password=tiger;data source=orcl";
                    con.Open();
                    using (OracleCommand cmd = new OracleCommand())
                        cmd.CommandText = "begin throwsomething;end;";
                        cmd.Connection = con;
                        try
                            cmd.ExecuteNonQuery();
                        catch (OracleException oe)
                            Console.WriteLine("caught " + oe.Message);
    OUTPUT
    ========
    caught ORA-20001: kaboom
    ORA-06512: at "SCOTT.THROWSOMETHING", line 3
    ORA-06512: at line 1

  • Handling apllication java.Exceptions

    I've developed an Weblogic WebService Application with several webservices inside.
    They are working fine but when a WebService throws a java Exception this exception is putted inside a SoapFaultException.
    After some research I figured that I should create my own Exceptions that inherits from SoapFaultException to best format the exception message
    my clients will receive, ok it is done and it's working. Now I need to handle all java Exceptions (witch were not throw by me) to put it in my own Exceptions witch inherits from soapFaultException. Does anybody know if I can implement an Exception handler that will capture all java Exceptions unhandled by my applicatio.
    I'm using WLS 9.2.

    Rethrow an exception and catch it in the call in JavaFX code?

  • How to handle null pointer exception

    dEAR ALL
    how to handle null pointer exception
    public void xxperscompmatchcase(OAPageContext pageContext,
    OAWebBean webBean,String cid,String pid)
    xxcrmleadperslastnameVOImpl vo=getxxcrmleadperslastnameVO();
    xxcrmleadcompnameVOImpl vo1=getxxcrmleadcompnameVO();
    vo.setWhereClauseParams(null);
    vo1.setWhereClauseParams(null);
    vo.setWhereClauseParam(0,pid);
    vo1.setWhereClauseParam(0,cid);
    vo.executeQuery();
    vo1.executeQuery();
    String compname="";
    String plname="";
    if(vo1.first().getAttribute("CompName")!=null)
    compname=(String)vo1.first().getAttribute("CompName");
    else
    compname="";
    if((String)vo.first().getAttribute("PersLastname")!=null)
    plname=(String)(String)vo.first().getAttribute("PersLastname");
    else
    plname="";
    OAFormattedTextBean p =
    (OAFormattedTextBean)webBean.findChildRecursive("personmatchcase");
    OAFormattedTextBean b =
    (OAFormattedTextBean)webBean.findChildRecursive("matchcase");
    b.setValue(pageContext,
    "The Lead is matched to company " + compname.toUpperCase());
    p.setValue(pageContext,
    "The Lead is matched to person " + plname.toUpperCase());
    it is going to null pointer exception
    how to handle this exception

    Hi,
    try
    //Write your logic here, which can generate any exception
    catch(Exception e)
    //Write your exception specific code here
    Regards,
    Reetesh Sharma

  • JVMDG215: Dump Handler has Processed Exception Signal 11.

    <html> <body>i am getting following exception on runtime in WSAD5.1.2 on WINDOWS XP OS , when using user defined method in place of stop() method of Thread class , that defined method contains interrupt() method .Anybody please let me know how to solve it <br>
    JVMDG217: Dump Handler is Processing a Signal - Please Wait.
    JVMDG303: JVM Requesting Java core file
    JVMDG304: Java core file written to C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\javacore.20070128.103223.412.txt
    JVMDG215: Dump Handler has Processed Exception Signal 11.
    </body></html>~

    Try to upgrade the JDK/VM

  • Help with New NumberFormat Exception

    Hello. I'm new to java and I can't figure this out. I'm trying to prevent customers from entering a negative value for the quantity or price with a (quantity <= 0)New NumberFormat Exception but it's not working. The negative values are being calculated in the grand total giving impossible results. -$4.50 can't be. How can I fix this problem?
    Is this the right forum for my question? If its not, please move this away.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import java.text.*;
    import java.text.DecimalFormat;
    public class BookOrderApplet extends Applet implements ActionListener
         //Declare variables.
         String Title, Author, answer;
         int quantity, numBooks, numTrans;
         double price, lastTot, subTotal, shipping, salesTax, total;
         //Create Date.
         Date currentDate = new Date();
         //Create Labels.
         Label dateLabel = new Label("" + currentDate);
         Label lblBookTitle = new Label("Book Title: ");
         Label lblAuthor = new Label("Author:");
         Label lblPrice = new Label("Price");
         Label lblQuantity = new Label("Quantity:");
         Label lblNumberOfLastTransactions = new Label("Number of Tansactions: 0");
         Label lblLastItemTotal = new Label("Last Item Total: 0");
         Label lblNumberOfBooks = new Label("Number of Books: 0");
         Label lblSubTotal = new Label("Subtotal: 0");
         Label lblSalesTax = new Label("Sales Tax: 0");
         Label lblShipping = new Label("Shipping: 0");
         Label lblOrderTotal = new Label("Order Total: 0");
         //Create TextFields.
         TextField txtTitle = new TextField(13);
         TextField txtAuthor = new TextField(13);
         TextField txtPrice = new TextField(20);
         TextField txtQuantity = new TextField(20);
         TextArea statusArea = new TextArea();
         //Create Buttons.
         Button calcButton = new Button("Calculate Total");
         Button resetButton = new Button("Reset Form");
         //Constructing the interface.
         public void init()
              //Add Labels.
              add(dateLabel);
              add(lblBookTitle);
              add(lblAuthor);
              add(lblQuantity);
              add(lblPrice);
              add(lblNumberOfLastTransactions);
              add(lblLastItemTotal);
              add(lblNumberOfBooks);
              add(lblSubTotal);
              add(lblSalesTax);
              add(lblShipping);
              add(lblOrderTotal);
              //Add Fields.
              add(txtTitle);
              add(txtAuthor);
              add(txtQuantity);
              add(txtPrice);
              //Add buttons.
              add(calcButton);
              add(resetButton);
              add(statusArea);
              setBackground(Color.white);
              statusArea.getPreferredSize();
              calcButton.addActionListener(this);
              resetButton.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if(e.getSource() == calcButton)
                   Title = txtTitle.getText();
                   Author = txtAuthor.getText();
                   quantity = getQuant();
                   price = getPrice();
                   transCount();
                   lastTot();
                   numBooks();
                   subTotal();
                   salesTax = salesTax();
                   shipping = shipping();
                   total = total();
                   answer = outFormat();
              else
              //resetButton should clear all the fields.
                        txtTitle.setText("");
                        txtAuthor.setText("");
                        txtQuantity.setText("");
                        txtPrice.setText("");
                        lblNumberOfLastTransactions.setText("Number of Tansactions: 0");
                        lblLastItemTotal.setText("Last Item Total: 0");
                        lblNumberOfBooks.setText("Number of Books: 0");
                        lblSubTotal.setText("Subtotal: 0");
                        lblSalesTax.setText("Sales Tax: 0");
                        lblShipping.setText("Shipping: 0");
                        lblOrderTotal.setText("Order Total: 0");
                        statusArea.setText("");
         //Prevent user from entering invalid quanity numbers.
         public int getQuant()
              try
                   quantity = Integer.parseInt(txtQuantity.getText());
                   if (quantity <= 0) throw new NumberFormatException();
              catch (NumberFormatException g)
                   statusArea.setText("Please enter a valid number for quantity.");
              return quantity;
         //Prevent user from entering invalid price numbers.
         public double getPrice()
              try
                    price = Double.parseDouble(txtPrice.getText());
                    if(price <= 0) throw new NumberFormatException();
              catch (NumberFormatException h)
                   statusArea.setText("Please enter a valid number for price.");
              return price;
         //Add up the number of transactions.
         public void transCount()
              numTrans = numTrans + 1;
              lblNumberOfLastTransactions.setText ("Number of Transactions: " + numTrans);
         //Previous Item Total.
         public void lastTot()
              DecimalFormat twoDigits = new DecimalFormat("#0.00");
              lblLastItemTotal.setText ("Last Item Total: $" + twoDigits.format(subTotal));
         //Add up the number of books.
         public void numBooks()
              numBooks = Integer.parseInt(txtQuantity.getText()) + numBooks;
              lblNumberOfBooks.setText ("Number of Books: " + numBooks);
         //Multiply price * quanity to get SubTotal.
         public void subTotal()
              DecimalFormat twoDigits = new DecimalFormat("#0.00");
              subTotal = price * quantity;
              lblSubTotal.setText("Subtotal: $" + twoDigits.format(subTotal));
         //Need to put a Sales Tax value later.
         public double salesTax()
              lblSalesTax.setText("Sales Tax: " + salesTax);
              return 0;
         //Shipping Total
         public double shipping()
              if (subTotal >= 50)
                   lblShipping.setText("Shipping: FREE!");
                   return 0;
              else
                   shipping = numBooks * 2;
                   lblShipping.setText("Shipping: " + shipping);
              return shipping;
         //GrandTotal
         public double total()
              DecimalFormat twoDigits = new DecimalFormat("#0.00");
              total = subTotal + shipping + salesTax;
              lblOrderTotal.setText("Order Total: $" + twoDigits.format(total));
              return total;
         //Put everything together.
         public String outFormat()
              DecimalFormat twoDigits = new DecimalFormat("#0.00");
              String answer = "You ordered: " + Title + " by " +  Author + "." + "     You purchased: " + quantity + " copies for $" + twoDigits.format(price) + " per item." + "    The Grand Total comes to: $" + twoDigits.format(total) ;
              statusArea.append("\n");
              statusArea.append(answer);
              return answer;
    }

    I suggest changing your code slightly. In the actionPerformed() method when you are calling other methods to parse the input, use a try/catch block around those methods. Something like thispublic void actionPerformed(ActionEvent e) {
              if(e.getSource() == calcButton) {
                   try {
                        Title = txtTitle.getText();
                        Author = txtAuthor.getText();
                        quantity = getQuant();
                        price = getPrice();
                        transCount();
                        lastTot();
                        numBooks();
                        subTotal();
                        salesTax = salesTax();
                        shipping = shipping();
                        total = total();
                        answer = outFormat();
                   } catch(NumberFormatException ne) {
              } else {
                   //resetButton should clear all the fields.
         }Then, inside the methods that parse the data, change the code so the exception is thrown to the caller, something like this     //Prevent user from entering invalid quanity numbers.
         public int getQuant() {
              boolean error = false;
              try {
                   quantity = Integer.parseInt(txtQuantity.getText());
              } catch(NumberFormatException ne) {
                   error = true;
              error = error | quantity <= 0;
              if (error) {
                   statusArea.setText("Please enter a valid number for quantity.");
                   throw new NumberFormatException();
              return quantity;
         }This allows the error to cause the program to skip calculating.
    I also think you have a logic problem with how you are calculating shipping.

  • Handling Java runtime exception on Vista OS

    Hello Forum members,
    This is regarding the handling of runtime exception on Vista machine with JRE 1.4.2_14.
    Iam working on client / server scenario where i need handle the run time exception say SocketExcpetion or IOException like "No Route to Host " exception whenever there is network connection problem with the server.
    Problem:
    On Windows 2000 and Windows XP OS , Iam able to get the Socket Exception from the server when there is network connection problem and based on this Iam displaying some error message to the user but on Vista am not able to catch these runtime exception since Vista OS is blocking the runtime excpetion thrown from the server or network.
    Please let me know how to configure the Vista OS to allow the runtime exception to be thrown to the user or how to handle the programmatically (using java ) on Vista OS to throw exception.
    Any suggestion is welcome
    Best regards,
    Sudhir

    I have heard that on Vista machine , by default the windows firewall will block all the runtime exceptions (especially the ones which are thrown from the server).
    This problem is with respect to Client/server scenario where the server will throw SocketException when there is network connection problem and on the client side i need to catch and handle this exception to display appropriate message to the end user.
    Background: Iam able to handle exception thrown from the server on Windows 2000 and Windows XP but on Vista am facing the above said problem i.e. am not able to get any exception from the server.

  • Exception Handling Standards -The exception Exception should never been thrown. Always Subclass Exception and throw the subclassed Classes.

    In the current project my exception handling implementation is as follows :
    Exception Handling Layer wise :
    DL layer :
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    throw;
    BL Layer
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    throw;
    UI Layer
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    Response.Redirect("ErrorPage.aspx", false);
    We have a tool to check the standards. And tool output is as follows :
    The exception Exception should never been thrown. Always Subclass Exception and throw the subclassed Classes.
    I need suggestions on how to implement the same according to standards.

    Your tool is wrong if it says to never throw Exception.  This was a common recommendation back in the .NET v1 days but has long since been thrown out.  It is perfectly fine to use Exception when you have a general exception that provides no information
    that an application can use to make an informed opinion.
    The general rules of exception throwing is to throw the most specific exception that makes sense. If there is no specific exception that applies and it would be useful for the caller to handle the exception differently than other exceptions then creating
    a custom exception type is warranted.  Otherwise throwing Exception is reasonable. As an example you might have an application that pulls back product data given an ID. There is no built in exception that says the ID is invalid. However an invalid ID
    is something that an application may want to handle differently than, say, an exception about the product being discontinued.  Therefore it might make sense to create an ItemNotFoundException exception that the application can react to.
    Conversely there is no benefit in having different exception types for disk full and disk quota met. The application will respond the same in either case.
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • Handling Java Mapping Exception in BPM Transformation step

    Dear SDN members,
    I have developed a File to File scenario using BPM as follows.
    Step 1:
    Sender file adapter picks the file from FTP server and using file content conversion mapped to XML structure.
    Step 2:
    BPM will recieve the XML payload , immediately in the block a transformation step is called with an interface mapping. In the interface mapping a Java mapping will be executed with certain data validations on the XML payload. If found any invalid data is there a suitable excptions will be raised . Here the transformation step should be catch the error and control should be sent to exception block to place the recived file as a error file.
    else if the transformation is executed with out any issues, the file will be placed in success folder.
    But in the transformation step, though java mapping thorwing exceptions, the control not going into exception block, instead it is continuing to next step i.e the file is placing in the success folder.
    Can anybody tell me, how to handle the exceptions raised in java mapping in the BPM transformation step?
    I have refered all the SDN blogs, forums related to this issue, but could not able to find the answer. Please help me?
    Thanks & Regards
    Vijayanand Poreddy

    Hi Abhishek,
    Once the file is picked from FTP server then sent to BPM,
    the BPM steps
    Step1:
    -->Recive
    Step 2:
    Block Starts
       ---Block Start: New Transaction
       ---Block End : New Transaction
       ---Exception : Error
    Step 3 
    Inside the Block
    Transformation Step
       --Interface Mapping: <IM Name>
       -- Check box ticked for Create New Transcation
       -- Exceptions
          --System Error: Error
       --Source Message: Message recieved in Recieve Step (Step 1)
    Step 4:
      --Send
      --Source Maessage: Output message from the Transformation Step
    Block End
    Inserted a Exception Branch for Block
    Steps inside Exception Branch
      -Control
        --Throw Alert
       --Alert Name
    In the above scenario
    The transformation step is not throwing error even my interface mapping going to error. The same transformation step if i place outside the block next to recieve step, then the transformation step is throwing error and BPM stops the process.
    Also, when transformation is inside the block, i have used the exception handling on the send step inside the block. here it is throwing error as the source message payload is empty. because in the preceding transformation step the interface mapping is failed due to which there the target will not be filled. But even though it is not entered into exception block.
    Regards
    Vijayanand Poreddy

  • Is there a way to handle custom java exception in OSB?

    For example, i created a exception that extends RuntimeException.
    My exception has a new field called "code".
    I want to handle this exception in Oracle Service Bus process and retrieve this code to throws another exception with a XML structure that includes the code.
    Is there a way to do that ?
    <con:fault xmlns:con="http://www.bea.com/wli/sb/context">
         <con:errorCode>BEA-382515</con:errorCode>
         <con:reason>Callout to java method "public static org.apache.xmlbeans.XmlObject ...</con:reason>
         <con:java-exception xmlns:con="http://www.bea.com/wli/sb/context">
             <con:java-content ref="jcid:33a6c126:14006f3df18:-7fd9"/>
         </con:java-exception>
         <con:location xmlns:con="http://www.bea.com/wli/sb/context">
             <con:node>optmusPipeline</con:node>                    
             <con:pipeline>optmusPipeline_request</con:pipeline>
             <con:stage>processStage</con:stage>
             <con:path>request-pipeline</con:path>   
         </con:location>
    </con:fault>
    it is not enough to recover the information i needed.

    Hi Sandro,
    I've got the same situation. I agree that returning xml from function is not a best choice as you have to manually check if return status is an error or not. Processing exception in error handler is better and this is how I do it:
    I am doing a java callout to a function that can throw exception. Then I add ErrorHandler to stage containing this callout (all the exception are caught here).
    In the error handler I check if $fault/ctx:java-exception is not null. If not then I pass thrown exception to my utility function that converts it to xml similar to yours:
    import org.apache.xmlbeans.XmlException;
    import org.apache.xmlbeans.XmlObject;
    public static XmlObject exceptionToXML(Throwable exception)
      throws XmlException {
      String xmlString = exceptionToString(exception);
      return XmlObject.Factory.parse(xmlString);
    public static String exceptionToString(Throwable exception) {
      String cause = "";
      if (exception.getCause() != null) {
      cause = exceptionToString(exception.getCause());
      return String
      .format("<exception><name>%s</name><description>%s</description>%s</exception>",
      exception.getClass().getName(), exception.getMessage(),
      cause);
    Calling exceptionToXML with $fault/ctx:java-exception/ctx:java-content returns:
    <exception>
         <name>pl.app.MyException</name>
         <description>Exception message</description>
    </exception>
    Then you can check the exception class (IF action: $exception/name/text() = "pl.app.MyException") and handle it accordingly.
    Good luck,
    Krzysiek

Maybe you are looking for