Catch an exception

Hi,
Sometimes the load request for an xml fails(timeout maybe)
and a message "unable to load data" is displayed in the flash
player on the mobile phone, how could I catch this exception to
manage the error/exception instead the message was shown???
I have tried the try-catch statement, but it seems that it
doesnt catch this kind of errors, does it?
Regards

I undestand the issue. The error message is displayed through
the device OS default message API . You should consider switching
your data from XML to value pairs (XML files are more cpu intensive
and usually cause more problems).

Similar Messages

  • Not able to catch the exception

    Hi,
    I'm trying to run an ADF page (Test.jspx) . The only page content I have is an embedded BI report.
    I have used a report executable in my page definition.
    A sample code snippet is:
    <executables>
    <biContent id="biExecBinding1" connectionId="TMBIPresentationServerConn" path="/shared/TMSharedFolders/MOT_SalesAccount" type="biReportContent" xmlns="http://xmlns.oracle.com/bi/report/bindings">
    </executables>
    Here TMBIPresentationServerConn is the name of the connection of the BI Server.
    If BI Server is down, on running my page , an exception is being thrown by the framework.
    I want to catch this exception and perform my own logic, but since i am using a binding context for report , i am not able to catch this exception.
    Could you please let me know how can i catch the exception if BI is down?
    Thanks
    Nutan

    (as I suspected from your first post)
    You are using a version of JDeveloper that isn't available to the general public, and are asking about it on a public forum. You should use the internal Oracle forum - I don't know the URL, because I am one of the unwashed general public ;)
    John

  • Why do I need to catch this exception?

    Hello all
    This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*; 
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;     
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;                                                                                                                                                                                                                         
    import static java.lang.Math.*;
    public class CalendarAssignment extends JFrame implements ActionListener
         int MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
         public JButton [] days = new JButton[43];
         private JLabel lbl, reminderlbl;
         private JPanel top, grid, remindercenter, reminderbottom;
         private JFrame reminderframe;
         private JTextField year1, reminderinput, dayno;
         private JComboBox months;
         private Container container;
         private JButton fetch, save, cancel;
         private Document doc;
         private File file;
         private Node node;
         private String year, month, day;
              public static void main( String[] args ) {
                   CalendarAssignment c = new CalendarAssignment( );
                   c.setSize( 400, 300 );
                   c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                   c.show( );
              public CalendarAssignment( ) {
                   int CurrentYear, CurrentMonth;
                   String YearString, MonthString, Now;
                   Date today;
                   container = getContentPane( );
                   container.setLayout( new BorderLayout( ) );
                   SimpleDateFormat DateFormatter;
                   DateFormatter = new SimpleDateFormat( "MM.yyyy" );
                   today = new Date( );
                   Now = DateFormatter.format( today );
                   MonthString = Now.substring( 0,2 );
                   YearString = Now.substring( 3,7 );
                   CurrentMonth = Integer.valueOf( MonthString );
                   CurrentYear = Integer.valueOf( YearString );
                   top = new JPanel( );
                        String [] items = { "January", "February", "March", "April", "May", "June",
                                      "July", "August", "September", "October", "November",
                                      "December" };
                        months = new JComboBox( items );
                        months.setEditable( false );
                        months.setSelectedIndex( CurrentMonth - 1 );          
                        year1 = new JTextField( );
                        year1.setText( YearString );
                        year1.setEditable( true );
                        year1.setHorizontalAlignment( year1.CENTER );
                        fetch = new JButton( "Fetch Month" );
                        fetch.addActionListener( this );
                        top.setLayout( new GridLayout( 1, 3, 20, 0 ) );
                        top.add( months );
                        top.add( year1 );
                        top.add( fetch );
                   grid = new JPanel( );
                        grid.setLayout( new GridLayout( 7, 7, 0, 0 ) );
                        String [] week = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
                        for ( int a = 0; a < 7; a ++ ) {
                                  JLabel lbl = new JLabel( week[a], JLabel.CENTER );
                                  grid.add( lbl );
                        for ( int i = 0; i < 42; i ++ ) {
                                  days[i] = new JButton( );
                                  grid.add( days[i] );
                                  days.addActionListener( this );
                        DrawCalendar( CurrentMonth, CurrentYear );
                        container.add( top, BorderLayout.NORTH );
                        container.add( grid, BorderLayout.CENTER );
              private void DrawCalendar( int SelectMonth, int SelectYear ) {
                        int DisplayMonthLength, Buttons;
                        String ButtonID = "";
                        int OffSet = MonthStart( SelectMonth, SelectYear );
                        DisplayMonthLength = MonthLength [SelectMonth - 1];
                        if ( SelectMonth == 2 )
                             DisplayMonthLength += LeapYear( SelectYear );
                        for ( Buttons = 1; Buttons < 43; Buttons ++ ) {
                             if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ) {
                                  ButtonID = "";
                                  days[Buttons-1].setEnabled( false );
                             else {
                                  ButtonID = Integer.toString( Buttons - OffSet );
                                  days[Buttons-1].setEnabled( true );
                        days[Buttons-1].setLabel( ButtonID );
                        grid.add( days[Buttons-1] );
              private int LeapYear( int year ) {
                        int FourHundred, OneHundred, Fourth;
                        FourHundred = year % 400;
                        OneHundred = year % 100;
                        Fourth = year % 4;
                        if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
                             return ( 1 );
                        else
                             return ( 0 );
              private int MonthStart( int Month, int Year ) {
                        int OffSet, LastMonths, BeforeOrAfter, Years;
                        int AllDays = 0;
                        int YearDays = 365;
                        int YearMonths = 12;
                        BeforeOrAfter = Year - 2006;
                        Years = abs( BeforeOrAfter );
                        if( BeforeOrAfter != 0 )
                             BeforeOrAfter = BeforeOrAfter / Years;
                        switch( BeforeOrAfter ) {
                             case 1:
                                  for( int a = 2006; a < Year; a ++ ) {
                                       AllDays += YearDays + LeapYear( a );
                                  AllDays += LastMonthsCalc( Month, Year );
                             break;
                             case -1:
                                  for( int a = 2005; a > Year; a -- ) {
                                       AllDays += YearDays + LeapYear( a );
                                  for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ) {
                                       AllDays += MonthLength[LastMonths - 1];
                                       if( LastMonths == 2 )
                                            AllDays += LeapYear( Year );
                             break;
                             default:
                                  if( Month > 1 )
                                       AllDays += ( LastMonthsCalc( Month, Year ) );
                        OffSet = AllDays % 7;
                        if( BeforeOrAfter ==( -1 ) )
                             return( 6 - OffSet );
                        else if( OffSet > 0 )
                             return( OffSet - 1 );
                        else
                             return( 6 );
              private int LastMonthsCalc( int Month, int Year ) {
                        int Counter;
                        int days = 0;
                        for( Counter = 1; Counter < Month; Counter ++ ) {
                             days += MonthLength[Counter - 1];
                             if( Counter == 2 )
                                  days += LeapYear( Year );
                        return( days );
              public void CreateReminder( String buttonID, String yearID, String monthID ) {
                        reminderframe = new JFrame( );
                        reminderlbl = new JLabel( );
                        reminderframe.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                        remindercenter = new JPanel( );
                             reminderlbl = new JLabel( "Please type in reminder to be saved for " + buttonID + " " + monthID + " " + yearID + ":", JLabel.CENTER );
                             reminderinput = new JTextField( 30 );
                             reminderinput.setHorizontalAlignment( reminderinput.CENTER );
                             reminderinput.setEditable( true );
                             remindercenter.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                             remindercenter.add( reminderlbl );
                             remindercenter.add( reminderinput );
                        reminderbottom = new JPanel( );
                             save = new JButton( "Save" );
                             save.addActionListener( this );
                             cancel = new JButton( "Cancel" );
                             cancel.addActionListener( this );
                             dayno = new JTextField( buttonID );
                             dayno.setEditable( false );
                             dayno.setEnabled( false );
                             dayno.show( false );
                             reminderbottom.setLayout( new FlowLayout( ) );
                             reminderbottom.add( save );
                             reminderbottom.add( cancel );
                             reminderbottom.add( dayno );
                        reminderframe.setSize( 500, 75 );
                        reminderframe.add( remindercenter );
                        reminderframe.add( reminderbottom );
                        reminderframe.pack( );
                        reminderframe.show( );
              public void SaveReminder( String dayID, String yearID, String monthID ) throws Exception {
                        file = new File( "Diary.xml" );
                        doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
                        String year = yearID;
                        String month = monthID;
                        String day = dayID;
                        //System.out.println( year );
                        //System.out.println( month );
                        //System.out.println( day );
                        CreateEntry( doc.getDocumentElement( ) );
                        writeXmlFile( );
              public boolean CreateEntry( Node node ) {
                        Node searchNode;
                        searchNode = getYear( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Year" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", year );
                        node = searchNode;
                        searchNode = getMonth( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Month" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", month );
                        node = searchNode;
                        searchNode = getDay( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Day" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", day );
                        node = searchNode;
                        String entry = reminderinput.getText( );
                        Node textNode = doc.createTextNode( entry );
                        node.appendChild( textNode );
                        return true;
              private Node getYear( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if(node.getNodeName( ).equals( "Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getMonth( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getDay( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private void writeXmlFile( ) throws Exception {
                   Source source = new DOMSource( doc );
                        Result result = new StreamResult( file );
                   Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
                   xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
                   xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
                   xformer.transform( source, result );
              public void actionPerformed( ActionEvent e ) {
                        String IDButton = e.getActionCommand( );
                        String IDYear = year1.getText( );
                        Object IDMonthObj = months.getSelectedItem( );
                        if( e.getSource( ) == fetch ) {
                             String YearText = year1.getText( );
                             int YearNumber = Integer.valueOf( YearText );
                             int MonthsIndex = months.getSelectedIndex( ) + 1;
                             DrawCalendar( MonthsIndex, YearNumber );
                        else if( e.getSource( ) == cancel ) {
                             reminderframe.hide( );
                        else if( e.getSource( ) == save ) {
                             String IDDay = dayno.getText( );
                             String IDMonth = String.valueOf( IDMonthObj );
                             SaveReminder( IDDay, IDYear, IDMonth );
                        else {
                             String IDMonth = String.valueOf( IDMonthObj );
                             Toolkit.getDefaultToolkit( ).beep( );
                             int n = JOptionPane.showConfirmDialog( null, "Set reminder on this date?", "Question", JOptionPane.YES_NO_OPTION );
                             if( n == JOptionPane.YES_OPTION ) {
                                  CreateReminder( IDButton, IDYear, IDMonth );
    If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;
    import java.util.*;
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    public class CallDOM
         Document doc;
         File file;
         Scanner input;
         int year, month, day;
         String currentYear, currentMonth;
         public static void main(String args[]) throws Exception
              CallDOM cd=new CallDOM();          
         CallDOM() throws Exception
              file=new File("Diary.xml");
              //create DOM from file
              doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
              input=new Scanner(System.in);
              System.out.println("1) Create entry");
              System.out.println("2) Read entry");
              System.out.println("3) Show Diary");
              System.out.println("4) Quit");
              int choice=input.nextInt();
              while(choice!=4)
                   switch(choice)
                        case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
                        case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
                        case 3: ShowDiary(doc.getDocumentElement());
                   System.out.println("1) Create entry");
                   System.out.println("2) Read entry");
                   System.out.println("3) Show Diary");
                   System.out.println("4) Quit");
                   choice=input.nextInt();
              writeXmlFile();
         public void GetDate()
              System.out.println("Enter date (dd mm yyyy)");
              day=input.nextInt();
              month=input.nextInt();
              year=input.nextInt();
         public boolean ReadEntry(Node node)
              node = getYear(node);
              if(node==null) return false;
              node = getMonth(node);
              if(node==null) return false;
              node = getDay(node);
              if(node==null) return false;
              node = node.getFirstChild();
              while(node!=null)
                   System.out.println(node.getNodeValue().trim());     
                   node=node.getNextSibling();
              return true;               
         public boolean CreateEntry(Node node)
              Node searchNode;
              searchNode = getYear(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Year");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(year));
              node = searchNode;
              searchNode = getMonth(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Month");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(month));
              node = searchNode;
              searchNode = getDay(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Day");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(day));
              node = searchNode;
              System.out.println("Enter Text");
              String entry=input.next();
              entry+=input.nextLine();
              Node textNode = doc.createTextNode(entry);
              node.appendChild(textNode);
              return true;               
         public void ShowDiary(Node node)
              Stack<Node> stack=new Stack<Node>();
              Node child;
              stack.push(node);
              while(!stack.empty())
                   node = stack.pop();
                   if(ProcessNode(node))
                        child = node.getLastChild();
                        while(child!=null)
                             stack.push(child);
                             child = child.getPreviousSibling();
         private boolean ProcessNode(Node node)
              if(node.getNodeName().equals("Year"))
                   currentYear=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Month"))
                   currentMonth=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Day"))
                   System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
                                            currentMonth+"/"+currentYear+": ");
                   node=node.getFirstChild();
                   while(node!=null)
                        System.out.println(node.getNodeValue().trim());
                        node=node.getNextSibling();
                   return false;
              return true;               
         private Node getYear(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Year")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
                             return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getMonth(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Month")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getDay(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Day")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private void writeXmlFile() throws Exception
            Source source = new DOMSource(doc);
            Result result = new StreamResult(file);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.setOutputProperty(OutputKeys.INDENT,"yes");
            xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
            xformer.transform(source, result);
    }My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
    Thanks for any advice!!

    Since your question didn't come with any relevant details, and since you have huge steaming piles of irrelevant code, all I can give is a general answer to "Why do I need to catch this exception?"
    [url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]Exception tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • Best Practice: JavaFX pattern for "Catching all Exceptions"

    Hi,
    what is on the current JavaFX Standard the best way to catch all Exceptions (centralized) within my JavaFX application...
    I read thread outside this Oracle Forum who recommend following:
    1. Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    --> catch all runtime exceptions
    2. http://stackoverflow.com/questions/12318861/javafx-2-catching-all-runtime-exceptions
    --> Implementing some source code who wrap the current GUI thread...
    3. I read something like:
    "JavaFX exception handling is almost identical to that in Java, apart from the fact that checked exceptions are handled in the same way as unchecked exceptions. This is good news for most Java programmers moving to JavaFX because you are no longer obliged to catch and handle exceptions."
    Sounds very good! But where/how can I do this ???
    Edited by: wschele on 19.02.2013 04:58
    Edited by: wschele on 19.02.2013 05:16

    No recommendation whats the best way to do it?
    Catching each Exception in different layers is boring ! :-(

  • Catching the exception thrown in a java class on a JSP front end

    I have a web service created in JAVA.. The modules throw certain exceptions and i am having auto generated JSP created from the WSDL's , which i can obviously edit. i want to catch these exceptions in this JSP page.. Any clue how to do this?
    Thanks.

    Nee333 wrote:
    I have a web service created in JAVA.. The modules throw certain exceptions and i am having auto generated JSP created from the WSDL's , which i can obviously edit. i want to catch these exceptions in this JSP page.. Any clue how to do this? It is not possible to catch the Exception in a JSP. You can however put any logging or even an if statement into your JSP to display the error or control the flow based on the error.

  • How to get details about Exception catched in Exception branch of the Block

    Hello Experts,
    Is it possible to get details about Exception catched in Exception branch of the Block in Integration Process (BPM)?
    In the Exception branch System Error is catched, but from time to time different type of System Errors are happening during sync call to WebService - Connection Timeout, Connection Refused, UnknownHost, etc.
    So the task is somehow to map the type of System Error to the response. I was trying to create a mapping using as source the message which is coming from the Adapter after the sync call, but the mapping is failing with "No Source Payload" error.
    Maybe the description is somewhere in Header or Dynamic configuration?
    Or it is possible to access it somehow with JAVA-maping?
    Thanks for your help!

    Hey,
          the message from the exception can be utilized by using alerts(in order to mail,sms r fax). but otherwise its not possible using mappings or container.
    check this link for alert configuration.
    /people/michal.krawczyk2/blog/2005/09/09/xi-alerts--step-by-step

  • Catching an exception in an JSF page

    Hi,
    I have made the following example:
    In my jsf page I have:
    <a4j:commandButton id="save" action="#{settings.save}"
    reRender="attributes" />
    <h:outputLabel value="Save" for="save" />
    <table width="100%" cellpadding="0" cellspacing="0">
    <!--
    <tr>
    <td> If exception occurs add extra buttons here for more actions
    </td>
    </tr>
    -->
    <tr>
    <td><ui:include src="/attributes.xhtml">
    <ui:param name="parent" value="#{settings}" />
    </ui:include></td>
    </tr>
    </table>
    In SettingsBean.java
    public void save() throws exception
    try
    doSomething();
    catch(Exception e)
    // catch the exception here and send it back to the jsf page????
    I want to be able to catch the exception when it occurs in my jsf page. If the exception arrises I want to add some extra buttons.
    Any ideas how to resolve this?
    Thanks in advance

    JSF does not work like JSP, even when using JSP with JSF, in that the execution is decoupled from the page being processed. So you cannot catch exceptions in JSF views.
    Assuming I have sufficiently confused you now, let me give you some ideas as to how to handle your situation. The usual way this is handled is to register a message when an exception occurs which are then displayed by <h:messages> or <h:message> components.
    However, this does not appear to be suitable for your purpose as you require specialized output when the exception occurs. So you could store a flag (or even the exception itself) in a backing bean and use the rendered property of all components to conditionally display your buttons. BUT you will need to take care that the dynamic value of the rendered property will be the same on the subsequent request or the actions for the buttons will not be queued.

  • Catching an exception (help)!!!

    Hi everyone, the problem i have is when the user enters a number that is out of bounds (higher or lower than the excepted values it should prompt the program to write to the screen "out of range, try again" or something along those lines.
    However, it instead just prints "error - program terminated" which is the message that should be printed when there is a different problem within the program.
    Can anyone help me get the program to print the correct messages, you can see what i mean from the code:
    import java.io.*;
    import java.util.ArrayList;
    public class FlatCost { 
        ArrayList floors = new ArrayList();
        public FlatCost(String filename)  {   
            try    {     
                readDataFromFile(filename);
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                int floor;
                int rooms;     
                String another = "y";     
                while(another.equalsIgnoreCase("y"))      {
                    System.out.print("\nEnter floor number (0 for ground): ");
                    floor = Integer.parseInt(in.readLine());      
                    if(floor < 0 || floor > floors.size())        {
                    System.out.println("floor out of range, try again");       
                else        {
                    System.out.print("\nEnter no. rooms: ");
                    rooms = Integer.parseInt(in.readLine());         
                    if(rooms < 0 || rooms > ((String[])floors.get(floor)).length)          {
                        System.out.println("rooms out of range, try again");         
                    else          {
                        System.out.println("\nThe cost of a "+rooms+"-room flat on floor "+floor+" is "+                                  
                        ((String[])floors.get(floor))[rooms+1]+" per month");
                        System.out.print("\nAnother? (y/n): ");
                        another = in.readLine();         
            catch(Exception e){
                System.out.println("error - program terminated");
    public void readDataFromFile(String filename)throws Exception {
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line = "";
    while((line = br.readLine()) != null)
    floors.add(line.split(" "));
    br.close();
    public static void main(String args[])throws IOException{
    new FlatCost(args[0]);
    }any help is appreciated
    thanks
    Sarah x

    I barely know where to begin.
    Start by printing out the stack trace when you catch an exception. That'll give you more information than the message you're printing out. You know the program is terminating - you need to know why.
    You're writing in a VERY procedural style. There's little or nothing object-oriented about what you're doing.
    You've got a bunch of stuff in that constructor that really doesn't belong there. You shouldn't have code to continuously ask a client for a floor and room number in a constructor. That really belongs in an application that drives the object, like the main method that you wrote.
    Your FlatCost can read in a file that contains floor/room/price information, but if I were writing the application I'd read it in and store it in the ArrayList as you've done. Then I'd have a getCost() method that would take floor and room count as parameters and return the total cost.
    Learning how to program is learning how to debug. I'd rewrite things a little bit and put System.out.println() statements into the code to narrow down exactly where the error was occurring and why. It won't take you long to figure it out. You don't even need a fancy debugger or IDE.

  • Catching an exception thrown from another thread

    I have a SocketServer that creates new threads to handle incoming clients. If one of the threads throw a SQLException is it possible to catch that exception in the SocketServer that created that thread.
    I tried implementing this code and I cannot get the server to catch an exception thrown in the thread. Are my assumptions correct?
    I was reading something about Thread Groups and implementing an uncoughtException() method, but this looked like overkill.
    Thanks for your time!
    Some Example code would be the following where the ClientThread will do a database query which could cause an SQLException. I'd like to catch that exception in my Socket Server
          try
                 new ClientThread( socketServer.accept() , host, connection ).start();
          catch( SQLException e )
                 System.out.println( "DataSource Connection Problem" );
                  e.printStackTrace();
          }

    hehe, why?
    The server's job is to listen for an incoming message from a client and pass it off to a thread to handle the client. Otherwise the server will have to block on that incoming port untill it has finished handling the client and usually there are many incoming clients continuously.
    The reason I would want to catch an exception in the server based on the SQLException thrown in the thread is because the SQLException is usually going to be due to the fact the datasource connection has become unavalable, or needs to be refreshed. This datasource connection is a private variable stored in the socket server. The SocketServer now needs to know that it has to refresh that datasource connection. I would normally try to use somesort of flag to set the variable but to throw another wrench into my dilemma, the SocketServer is actually its own thread. So I can't make any of these variables static, which means I can't have the thread call a method on teh socket server to change the status flag. :)
    I guess I need implement some sort of Listener that the thread can notify when a datasource connection goes down?
    Thanks for the help so far, I figured java would not want one thread to catch another thread's exceptions, but I just wanted to make sure.

  • Catching an exception within a JSP

    Hi all,
    I need to catch an exception in a JSP before the errorPage handles it. Have tried with try-catch but it seems like the exception is thrown to the errorPage anyway. Do you know of any technique to handle this.
    In other words: I would like to specify program logic for one exception within the JSP itself. Let us say Customer.Authenticate() throws an Exception when the given e-mail is not included in customer-DB. I would like to append logic instead of being redirected to errorPage.
    Anyone done this, can it even be done?
    ,Chr

    I would try keeping the error page as it is and still adding the logic in the catch block. If that does not help, then remove the error page and use <jsp:forward> (after your logic) in the catch block to explicitly go to the error page.
    or if you want to process that logic anyways in case of an exception, try adding your logic in the finally block.

  • Write and read txt files and catch the exceptions

    hey everyone, im in a bit of a bind. im trying to set up this try catch statement. here is what i have for code so far.
    import java.util.Scanner;
    import java.io.*;
    public class Warning
        //   Reads student data (name, semester hours, quality points) from a
        //   text file, computes the GPA, then writes data to another file
        //   if the student is placed on academic warning.
        public static void main (String[] args)
         int creditHrs;         // number of semester hours earned
         double qualityPts;     // number of quality points earned
         double gpa;            // grade point (quality point) average
         String line, name, inputName = "students.dat";
         String outputName = "warning.dat";
         try
              Scanner FileScan1 = new Scanner (new File("students.dat"));
              // Set up scanner to input file
              // Set up the output file stream
              // Print a header to the output file
              outFile.println ();
              outFile.println ("Students on Academic Warning");
              outFile.println ();
              // Process the input file, one token at a time
              while (FileScan1.hasNext())//there is another line...
                  {               // Get the credit hours and quality points and
                   // determine if the student is on warning. If so,
                   // write the student data to the output file.
              // Close output file
         catch (FileNotFoundException exception)
              System.out.println ("The file " + inputName + " was not found.");
         catch (IOException exception)
              System.out.println (exception);
         catch (NumberFormatException e)
              System.out.println ("Format error in input file: " + e);
    }I am pretty sure the layout is good to go, but first and foremost that try statement is hanging me up. Could someone give me some suggestions about how i should set this up.
    i want to read in this students.dat file, then output another file called warning.dat.
    Thanks i really appreicate the help.

    no, i was really hoping to just see if the way it is
    set up it will be doable, that way i wouldn't be
    working on code that was impossiable to sort through
    properlyFair enough.
    One thing I'd suggest is that if you're really basically only going to be printing the exceptions, and since that is the top-level method (main) --
    I'd instead just add some "throws" clauses to main, get rid of the try/catch stuff, and just let the VM handle the exceptions for you. It will print them, just like you're doing, except that it will also print the stack traces, which you are not doing.
    If you're going to handle exceptions, it's better to actually do something about them rather than just print them - otherwise you might just as well let the runtime do that for you.

  • How can I catch the exception type c = type i?

    How can I catch the exception and display the error message when I assign the u2018ABC123u2019 value to an int data type.
    Code is as follow.
    REPORT  zfsl_sum_functions.
    DATA: cin(50),
          cout(50),
          iin TYPE i,
          iout TYPE i,
          etext TYPE string.
    cin = '123ABC'.     " how can i catch this
    iout = cin.
    WRITE: iout.

    The CATCH-ENDCATCH statement is obsolete as of release was620. You should use TRY. CATCH. ENDCATCH.
    The exception that will be raise is CX_SY_CONVERSION_NO_NUMBER, so you have to catch that exception or a super class of this exception class.
    REPORT zfsl_sum_functions.
    DATA: cin(50),
    cout(50),
    iin TYPE i,
    iout TYPE i,
    etext TYPE string.
    DATA: rf_cx_error TYPE REF TO CX_SY_CONVERSION_NO_NUMBER,
            errortxt TYPE string.
    TRY.
        cin = '123ABC'. " how can i catch this
        iout = cin.
        WRITE: iout.
      CATCH CX_SY_CONVERSION_NO_NUMBER INTO  rf_cx_error.
        errortxt = rf_cx_error->get_text( ).
        WRITE errortxt.
    ENDTRY.

  • How does one catch WebUtil exceptions?

    We are automating Microsoft Word using the CLIENT_OLE2 built-in. In some cases, our requirements demand that Word be running in a visible window. One of our processes automates the same Word session repeatedly -- when a user unwittingly closes Word, and our process attempts to further automate the now-closed Word session, exception WUO-714 is raised, and an alert is displayed.
    The WebUtil documentation indicates that logging can be configured silently log exceptions without an alert being displayed, but I cannot find a way to actually catch them. Our process could recover gracefully from the scenario described above by simply relaunching Word -- if only we could catch the exception!
    Has anyone else already figured out to accomplish this?
    Thanks,
    Eric Adamson
    State of Michigan

    Herzliche Begrüßen Gerd,
    Thanks for your reply -- the error occurs in a PL/SQL block. Since my initial post, I have discovered that my test code contained a WHEN OTHERS THEN NULL statement. (When coding blocks, I often complete them with NULL statements, as I compile very often, to simplify tracking down errors. This strategy works wonderfully, when I remain focused, but the distractions of researching WebUtil errors evidently led me to overlook my mistake. Perhaps others may learn from my embarrassing lesson.)
    In any case, I am now able to catch the exception, and to handle it appropriately. Most importantly, readers should note that it was necessary to change the WebUtilErrorMode entry in FORMSWEB.CFG. By default WebUtilErrorMode=Alert -- this causes the error alerts to pop up, regardless of whether/not the exception ultimately gets handled. I have set WebUtilErrorMode=Console.
    Thanks for reading, and congratulations on winning the match with Costa Rica!
    Regards,
    Eric Adamson
    Lansing, Michigan

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • How to throw or catch sql exception for executeReader sql adapter

    Wcf sql adapter was created and executeReader was used.
    When an invalid sql statement was constructed and send it to wcf sql adapter, it will hanging there, and no response. No exception was catched even though send chape  was inside a catch block. How can I catch this kind of exception
    or throw this exception ? I need to give client an exception resposne.
    thanks
    Gary

    I used scope with exception handle which has Exception object type: "System.SystemException".
    I guess this type "System.SystemException" can catch any exception, including sql exception. Maybe I am wrong. I got error from window event:
    A message sent to adapter "WCF-Custom" on send port "WcfSendPort_SqlAdapterBinding_DalCore_Custom" with URI "mssql://shig-quad-2k3e1//DataSourceOne?" is suspended.
     Error details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.
    Server stack trace:
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
       at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
     MessageId:  {B24EF5B8-298A-4D4F-AA98-5E639361A7DB}
     InstanceID: {F8924129-265B-4652-B20E-8D25F8F20A51}
    If  "System.SystemException" can't catch all exception, which type can catch all exception ? I want to catch all exception in this catch block.
    thanks
    Gary

  • Urgent: How can I catch the exception when application exit by accident

    Can anyone give me advice and idea?
    I want to catch the exception when application goes down by accident for example: Power off, turn off the machine without closing the appliction properly.
    Because I want to notify the server and remove it from register.
    How can I do this????
    Please help,
    Thanks very mich,
    Peter

    Shrubz,
    I tested my application as follows:
    1. start rmiregistry
    2. start rmi server
    3. start two clients
    I printed out the client's object information as below:
    first clinet:
    RemoteObserver is com.ss8.qos.qcsm.policy.policyui.PanelMain_Stub[RemoteStub [ref: [endpoint:[192.168.70.237:4706](remote),objID:[-73a6662b:e75af455a5:-8000, 0]]]]
    second client:
    RemoteObserver is com.ss8.qos.qcsm.policy.policyui.PanelMain_Stub[RemoteStub [ref: [endpoint:[192.168.70.237:4711](remote),objID:[-73a6665a:e75af48703:-8000, 0]]]]
    Now I stop the second client by clicking ^C (ctrl c)
    I noticed that this client has not been removed from the server register (Vector).
    next, I am working on first client for example add one record. After server received this record, it will update all clients who have already registered with server. Because now in the server register there are two clinets (first and second), so it will try to update two clients. The exception will be thrown when server tries to update second client which has already been stoped. I used printStackTrace() to print out the message as follow:
    Catch ConnectException
    Connection refused to host: 192.168.70.237; nested exception is:
         java.net.ConnectException: Connection refused: no further information
    java.rmi.ConnectException: Connection refused to host: 192.168.70.237; nested exception is:
         java.net.ConnectException: Connection refused: no further information
    java.net.ConnectException: Connection refused: no further information
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
         at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:125)
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:112)
         at java.net.Socket.<init>(Socket.java:269)
         at java.net.Socket.<init>(Socket.java:98)
         at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:29)
         at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:124)
         at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:497)
         at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:194)
         at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:178)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:87)
         at com.ss8.qos.qcsm.policy.policyui.PanelMain_Stub.update(PanelMain_Stub.java:53)
         at com.ss8.qos.qcsm.policy.policydb.Observable.performNotify(Observable.java, Compiled Code)
         at com.ss8.qos.qcsm.policy.policydb.Observable.notifyObservers(Observable.java:71)
         at com.ss8.qos.qcsm.policy.policydb.PolicyServer.ServerAddPolicy(PolicyServer.java:102)
         at java.lang.reflect.Method.invoke(Native Method)
         at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:237)
         at sun.rmi.transport.Transport$1.run(Transport.java:140)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.rmi.transport.Transport.serviceCall(Transport.java:137)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:422)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:634)
         at java.lang.Thread.run(Thread.java:479)
    *** end here ***
    I don't see any information related to object ID. How can I handle this?
    Please give me suggestion.
    Many Thanks,
    Peter

Maybe you are looking for

  • Node Function help required in XML message mapping !!

    Hi Brilliants, Source Message     <ROOT>               0..1          <OUTPUT>          0..n          <Group_N1>           0..n     <Header>             <H02_N1_DTM>                           0..1       DTM_Y2K_DATE     0..1          <Group_LIN>      

  • Calendar dropped from Calendars regularly with ios6

    I have multiple exchange calendars linked to the iPhone Calendars.  Once I upgraded to ios6, one of calendars is regularly (multiple times a day) dropped from being displayed.  When this happens, I need to select the "Calendar" button in the upper le

  • Is it possible DLSW with remote ack for LLC2.?

    Hello.: In the following env I have an SNI connection: 3745-Tokenring/2612-FrameRelay-2612/Tokenring-OSA. the 2612 is DLSW. I have noticed, sometimes,when there is a HW problem in the right side, the 2612left, maintains the LLC2 session with R/Rs and

  • Cisco Works LMS 3.1 Integration with ACS v5.2

    Hello Experts, our customer has a working integration with the Cisco Works LMS 3.1 and an ACS v3.3 as it is described in this document: http://www.cisco.com/en/US/prod/collateral/netmgtsw/ps6504/ps6528/ps2425/prod_white_paper0900aecd80613f62.html Now

  • I can't download and/or install ios 4.2 ot my iphone 4.

    I can't download full iOS 4.2 Software and can't install. The screen on my computer is display: "There was a problem downloading the software for the iphone. The network connection time out. Make sure your network settings are correct and your networ