Catching exceptions

Maybe a stupid question but is there any common practice when it comes to handling exceptions in Java? Should I declare throws for the whole method or should I use a try-catch construction? I can see the advantage of passing exception to the calling methods but this means that many methods must be throwables or catch the exceptions so it's kind of a circle of exceptions...
/P

You usually don't want to do
catch (Exception e) {}
Somewhat less onerous is
catch (Exception e) { //handle it }
Normally what you'd do is define your own exception classes that extend Exception. A common approach is to use a package-based hierarchy, with specific exceptions for specific types of errors.
// package com.mycompany.dbstuff might have these
public class DatabaseException extends Exception { /*...*/}
public class NoSuchTableException extends DatabaseException { /*...*/ }
public class  LoginFailedException extends DatabaseException { /*...*/}
// package com.mycompany.accountmanagement package may have these
public class AccountException extends Exception {/*...*/}
public class IllegalAccountNumberExceptoin extends AccountException {/*...*/}
// etc.Each exception simply has constructors that call super(same args), and possibly the ability to take another Throwable as a constructor arg, which is then mapped to a member variable so you can later call getCause() or getWrappedException to see which exception led to this one.
At any given layer, you catch exception thrown by the layers it uses, and wrap them in an exception for your current layer.
// in the AccountClass
public AccountInfo getAccountInfo(int acctId) throws AccountException {
    if (acctId < 0) {
        throw new IllegalAccountNumberException("No negative account numbers");
    try {
        database.login(uname, passwd);
        databse.getAccountInfo(acctId);
    catch (DatabaseException exc) {
        exc.printStackTrace();
        throw new AccountException(exc);
}This way, the user of the accountmanagement package doesn't need to know what database package accountmanagement uses. If I call an accountmanagement method, I only have to deal with an account relatd exception. If it's IllegalAccountNumber, I can prompt the user to reenter the acct number. If it's other, I can say "Couldn't retrieve account info, please try again" or some such thing.
And yes, I know, if the login failed, you'd want to propagate that, so the user could reenter the password. I'd make a separate AccountLoginFailedException and wrap that around the DBLoginFailed, because the user of the Account class is trying to access the account, not the database.
Also, you often do want to print stack traces. Not in your user's face--off in a log file somehwere. If you've got exceptions that are ocurring for reasons other than user typos, you want to record as much info as you can about them.

Similar Messages

  • How to catch exception into a String variable ?

    I have a code
    catch(Exception e)
                e.printStackTrace();
                logger.error("\n Exception in method Process"+e.getMessage());
            }when i open log i find
    Exception in method Process null.
    But i get a long error message in the server console !! I think thats coming from e.printStackTrace().
    can i get the error message from e.printStackTrace() into a String variable ?
    I want the first line of that big stacktrace in a String variable.
    How ?

    A trick is to issue e.printStackTrace() against a memory-based output object.
    void      printStackTrace(PrintStream s)
             // Prints this throwable and its backtrace to the specified print stream.
    void      printStackTrace(PrintWriter s)
    //          Prints this throwable and its backtrace to the specified print writer.Edited by: BIJ001 on Oct 5, 2007 8:54 AM

  • How to catch exception while validating the username and password in hbm

    Hi,
    I do want to set the username and password dynamically in hibernate.cfg.xml
    Here below is my configuration file.
    {code<hibernate-configuration> 
    <session-factory> 
           <property name="hibernate.bytecode.use_reflection_optimizer">false</property> 
           <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
           <property name="hibernate.connection.pool_size">10</property> 
           <property name="show_sql">true</property> 
           <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property> 
           <property name="hibernate.hbm2ddl.auto">update</property> 
           <property name="current_session_context_class">thread</property> 
           <property name="show_sql">true</property> 
         </session-factory> 
    </hibernate-configuration>{code}
    Also im getting that session factory object like the below code.
    public class Sessions {        private static SessionFactory sessionFactory;      private static Configuration configuration = new Configuration();        static {          try {              String userName = GuigenserviceImpl.userName;              String password = GuigenserviceImpl.password;              String hostName = GuigenserviceImpl.hostName;              String portNo = GuigenserviceImpl.portNo;              String sId = GuigenserviceImpl.sId;                  configuration                      .setProperty("hibernate.connection.username", userName);              configuration                      .setProperty("hibernate.connection.password", password);              configuration.setProperty("hibernate.connection.url",                      "jdbc:oracle:thin:@" + hostName + ":" + portNo + ":" + sId);                try {              configuration.configure("/hibernate.cfg.xml");              sessionFactory = configuration.buildSessionFactory();              GuigenserviceImpl.strAccpted = "true";              }              catch (Exception e) {                    e.printStackTrace();                  GuigenserviceImpl.strAccpted = "false";              }            }          catch (HibernateException hibernateException) {              GuigenserviceImpl.strAccpted = "false";              hibernateException.printStackTrace();          }          catch (Throwable ex) {                GuigenserviceImpl.strAccpted = "false";              ex.printStackTrace();              throw new ExceptionInInitializerError(ex);          }      }          public static SessionFactory getSessionFactory() {          return sessionFactory;      } 
    So, in this above scenario, suppose if im giving the wrong password means exception should be caught and the string variable "GuigenserviceImpl.strAccpted" should be assigned to false.
    But im getting the SQL Exception only in console like wrong username and password. And finally i couldn't able to catch the exception in Sessions class, static block.
    Anyone can help me in catching that SQL Exception in my Sessions class and i need to handle that SQL Exception in my class.
    Im getting this following exception message in my console.
      INFO: configuring from resource: /hibernate.cfg.xml  Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration getConfigurationInputStream  INFO: Configuration resource: /hibernate.cfg.xml  Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration doConfigure  INFO: Configured SessionFactory: null  Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure  INFO: Using Hibernate built-in connection pool (not for production use!)  Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure  INFO: Hibernate connection pool size: 10  Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure  INFO: autocommit mode: false  Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure  INFO: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@192.168.1.12:1521:orcl  Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure  INFO: connection properties: {user=scott, password=****}  Apr 6, 2009 2:47:01 PM org.hibernate.cfg.SettingsFactory buildSettings  WARNING: Could not obtain connection metadata  java.sql.SQLException: ORA-01017: invalid username/password; logon denied        at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)      at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)      at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:204)      at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)      at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406)      at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)      at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:799)      at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:368)      at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)      at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)      at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)      at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)      at java.sql.DriverManager.getConnection(DriverManager.java:525)      at java.sql.DriverManager.getConnection(DriverManager.java:140)      at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)      at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)      at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2073)      at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1298)      at com.beyon.ezygui.server.Sessions.<clinit>(Sessions.java:39)      at com.beyon.ezygui.server.GuigenserviceImpl.testRPC(GuigenserviceImpl.java:322)      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    Thanks in advance.
    Thanks & Regards,
    Kothandaraman N.

    Hi,
    Myself hardcoded that username and password checking like the below code.
    String name = loginData.get("userName").toString();
              String pswd = loginData.get("pswd").toString();
              String hstName = loginData.get("hName").toString();
              String prtNo = loginData.get("portNo").toString();
              String sid = loginData.get("sId").toString();
              SessionFactory sessionFactory = null;
              try {
                   if (name.trim().equals(userName) && pswd.trim().equals(password)
                             && hstName.trim().equals(hostName)
                             && prtNo.trim().equals(portNo) && sid.trim().equals(sId)) {
                        sessionFactory = Sessions.getSessionFactory();
                        strAccpted = "true";
                   } else {
                        strAccpted = "false";
              } catch (Exception e) {
                   e.printStackTrace();
                   strAccpted = "false";
              }I have my own values in string objects, then comparing that values with the values from login form. If both values are matching, then i will do configurations in hibernate.
    ResourceBundle resourceBundle = ResourceBundle
                   .getBundle("com.beyon.ezygui.server.Queries");
         public static final String connection_url = resourceBundle
                   .getString("connection.url");
         public static final String userName = resourceBundle.getString("userName");
         public static final String password = resourceBundle.getString("password");
         public static final String hostName = resourceBundle.getString("hostName");
         public static final String portNo = resourceBundle.getString("portNo");
         public static final String sId = resourceBundle.getString("sId");The above are the String objects i'm checking for the match with values from login form.
    Thanks & Regards,
    Kothandaraman N.

  • How to catch exception of JMS when call onMessage()?

    I write a consumer client implement onMessage(),
    in my main() method ...
    try {
    _adapter = new Adapter(checkConsumer,env);
    _adapter.setSelector("client = 'Receive1'");
    _adapter.start();
    System.out.println("Hello...");
    } catch(Exception e) {
    _adapter = null;
    System.out.println("Unable to start adapter: " + e.getMessage());
    _adapter.start() will call onMessage() my onMessage like this
    public void onMessage(Adapter adpt, Message message) {
    try {
    if(message instanceof TextMessage) {
    // Write the text out as read String text = ((TextMessage)message).getText();
    // Do CHECK Process adpt.demoOut("Receive CHECK Text is :" + text);
    //System.out.println("class name is " + consumerName);
    } else {
    // This is just a message (no particular type) } } catch (Exception e) {
    try {
    adpt.warn("Error outputing data: " + message.getJMSMessageID());
    } catch(Exception ignore) {
    } adpt.warn("\tError: " + e.getMessage());
    // Do some exception process }
    If the JMS Server shutdown, how can I catch the exception?

    You might want to try with exception listener that JMS specification provides.

  • How to catch exception when have max connection pool

    hi,
    i have define in oracle user that i could have max 10 sessions at the same time.
    I have jdbc datasource & connection pool defined at glassfish server(JSF application).
    now, if in application is too many queries to the database then i have error: nullpointer exception - becouse when i try to do:
    con = Database.createConnection(); - it generates nullpointer exception becouse there isn't free connection pool
    i try to catch exception like this:
    public List getrep_dws_wnioski_wstrzymane_graph() {     int i = 0;     try {     con = Database.createConnection();     ps =    (Statement) con.createStatement();     rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow");     while(rs.next()){       rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));       i++;     }     } catch (NamingException e) {         e.printStackTrace();     } catch (SQLException e) {         e.printStackTrace();     } catch (NullPointerException e) {         e.printStackTrace();         throw new NoConnectionException();  // catch null 1     } finally {     try {         con.close();     } catch (SQLException e) {         e.printStackTrace();     } catch (NullPointerException e) {         e.printStackTrace();         throw new NoConnectionException();  // catch null 2     }     } return rep_dws_wnioski_wstrzymane_graph; }
    but at line:
    con.close();
    i have nullpointerexception
    and
    at line
    throw new NoConnectionException(); // catch null 2
    i have: caused by exception.NoConnectionException
    what's wrong with my exception class? how to resolve it?
    public class NoConnectionException extends RuntimeException{     public NoConnectionException(String msg, Throwable cause){       super(msg, cause);     }     public NoConnectionException(){       super();     } }
    at web.xml i have defined:
    <error-page>         <exception-type>exception.NoConnectionException</exception-type>         <location>/NoConnectionExceptionPage.jsp</location>     </error-page>

    thanks,
    i did it and i have error:
    java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: ORA-02391: exceeded simultaneous SESSIONS_PER_USER limit
    at com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:115)
    at logic.Database.createConnection(Database.java:37): conn = ds.getConnection();
    public class Database {
         public static Connection createConnection() throws NamingException,
                    SQLException {
                Connection conn = null;
                try{
                    Context ctx = new InitialContext();
              if (ctx == null) {
                   throw new NamingException("No initial context");
              DataSource ds = (DataSource) ctx.lookup("jdbc/OracleReports");
              if (ds == null) {
                   throw new NamingException("No data source");
              conn = ds.getConnection();  // here's exception when max connections to database
              if (conn == null) {
                   throw new SQLException("No database connection");
                } catch (NamingException e) {
                    e.printStackTrace();
                    throw new NoConnectionException(); 
             } catch (SQLException e) {
                 e.printStackTrace();
                    throw new NoConnectionException(); 
                catch (NullPointerException e) {
                 e.printStackTrace();
                    throw new NoConnectionException();  // obsluga bledy na wypadek jesli braknie wolnych polaczen do bazy
            return conn;
    }and at my ealier code i have error:
    at logic.GetDataOracle.getrep_dws_wnioski_wstrzymane_graph(GetDataOracle.java:192)
    at line: con = Database.createConnection();
    in code:
    public List getrep_dws_wnioski_wstrzymane_graph() {
        int i = 0;
        try {
        con = Database.createConnection();
        ps =    (Statement) con.createStatement();
        rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow");
        while(rs.next()){
          rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));
          i++;
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new NoConnectionException();
        } finally {
        try {
            if(con != null)
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new NoConnectionException(); 
    return rep_dws_wnioski_wstrzymane_graph;
    }so what's wrong?
    i have limit max sessions 10 at oracle so i set at my connection pool 5 connections as max. But when i get max 5 sesssins and try to execute next query then i can't catch exception..

  • How to catch exception thrown from a function module?

    Hi all,
             When we are calling a function module from JSPDynpage setting some import parameters, If in some case an exception is thrown in the function module.  How can we catch the same exception in the JSPDynpage program?
    Thanks & Regards,
    Ravi

    Hi Ravi
                                    Try this
                                                try
                    Object retMsgs = output.get(bapiretrunmsgobject);
                      if(result != null )
    IrecordSet rmsg = (IrecordSet) result
                   catch(Exception ex)
                        printException(ex, "Error getting function result");
    Lemme know for any further questions.
    Regards
    Praveen

  • SFTP adapter error : Catching exception calling messaging system

    Error: com.aedaptive.sftp.adapter.SFTPException : Not all messages were delivered succesfully
      Could not deliver message to XI: com.sap.aii.af.lib.mp.module.ModuleException: senderChannel 'ca09269447583427adc545f8c23d244b': Catching exception calling messaging system
    This is error message which i get in sender communication channel while working  with SFTP adapter.

    Hi Pooja,
    I think it would be better to add getcause() to get the cause of the issue.
    Ref: http://help.sap.com/javadocs/pi/SP3/xpi/com/sap/aii/af/lib/mp/module/ModuleException.html
    Thanks,

  • Catch Exception shape - working in inner loop but not in outer loop

    Hello,
    I'm trying to use the catch exception shape for the first time.  My orchestration has 3 loops.  I'll call them loop1, loop2, loop3 where loop3 is my inner most loop.  I'm able to catch the exact same error on the inner most loop3 but the outer
    loop2 doesn't catch it and just puts a warning in the event viewer ( have no catch or scope on loop1 yet). 
    I can't figure out what the difference is.  
    The one that is not caught just has the dehydrated message and orchestration saying it will try again.  then 5 mins later it does log an error and terminates but my catch is still not catching it.
    Below in bold is the 'uncaught' warning message and the caught error message respectively.  They look exactly the same to me, so why would the inner be caught but outer NOT caught?  they're both catching the same type which is System.SystemException.
     I couldn't get either to catch a System.FormatException but that's a different issue I'll solve later.
    this is the warning from the UNCAUGHT error:
    The adapter failed to transmit message going to send port "WcfSendPort_SqlAdapterBinding_TypedProcedures_dbo_uspEncounterAdd" with URL "mssql://sqldev1//AllianceDB?InboundId=uspEncounterAdd". It will be retransmitted after the retry interval
    specified for this Send Port. 
    Details:"Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "sTransactionId" is invalid according to the expected SqlDbType BigInt. ---> System.FormatException: Input string was
    not in a correct format.
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
       at System.Int64.Parse(String s, NumberStyles style, IFormatProvider provider)
       at Microsoft.Adapters.Sql.MetadataHelper.ConvertXmlValueToDotNetObject(String xmlString, String fieldParameterName, SqlDbType sqlDbType, Int32 maxLength, Int32 precision)
       --- End of inner exception stack trace ---
    Server stack trace: 
       at System.Runtime.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)".
    This is the error message that I'm writing to the event viewer when CATCHING the error in loop3:
    Error from ScopeGetEncounterResponse: message = An error occurred while processing the message, refer to the details section for more information 
    Message ID: {1781C639-DB28-4306-B701-783E069A0403}
    Instance ID: {8E1084F2-00EE-43B2-A112-BF80702A167A}
    Error Description: Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "sRefID" is invalid according to the expected SqlDbType BigInt. ---> System.FormatException: Input string was not
    in a correct format.
       at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
       at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
       at System.Int64.Parse(String s, NumberStyles style, IFormatProvider provider)
       at Microsoft.Adapters.Sql.MetadataHelper.ConvertXmlValueToDotNetObject(String xmlString, String fieldParameterName, SqlDbType sqlDbType, Int32 maxLength, Int32 precision)
       --- End of inner exception stack trace ---
    Server stack trace: 
       at System.Runtime.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)
    Thank you so much for your excellent advice!
    Jean Stiles
    jRenae.s

    It turns out that my outer loop2 was catching the error.  It was just retrying 3 times before it would catch it (I forgot that I had set the retry count to 0 on the loop3 inner port).  I was so impatient that I was stopping my orchestration
    before it was actually catching it!
    jRenae.s
    HI jRenae.s,
    Congratulations! I’m glad to hear that you have solved this issue by yourself, and it is very appreciated to share your solution to us. It will be helpful for others, and welcome to post your question on this forum.
    Best regards
    Angie
    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.

  • Help Me, How to catch exception thrown from ejbStore

    Hi,
    I am working on application running on Iplanet Application Server 4.0. Problem is the application exception thrown from the ejbStore don't reach the calling servlet, calling servlet receive TransactionRollback exception which is system exception. But there is no sign of my application exception thrown from ejbStore. Can anybody tell me how I can get my ApplicationException thrown from ejbStore in my calling servlet.
    I am calling entity beans set method in servlet and in entity bean ejbStore method I am throwing Application exception.
    in entity bean
    public void ejbStore() throws MyException
    if(true) throw new MyException();
    in servlet
    try {
    MyEntityHome home = .......
    MyEntityRemote remote = home.findBy.....
    remote.setMyValue(MyValue value); //Transaction required Container managed
    }catch(MyException e) {
    e.printStackTrace(); // Not cahcing My Exception
    }catch(Exception e) {
    e.printStackTrace(); //catching TransactionRolledBackException
    Thanks
    Shakti

    Hi Ravi
                                    Try this
                                                try
                    Object retMsgs = output.get(bapiretrunmsgobject);
                      if(result != null )
    IrecordSet rmsg = (IrecordSet) result
                   catch(Exception ex)
                        printException(ex, "Error getting function result");
    Lemme know for any further questions.
    Regards
    Praveen

  • How to catching exceptions 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.so ,somebody help me ,thk.

    hi,ejp,this is my scene:
    getHttpParty(String name) is a method get some information from a web site,this maybe cause many times.now this method is called in my main(String args[]) method.
    i want to terminate getHttpParty if it runs 2s, can you give some simple code to do this.
    thank you very much.
    Edited by: user5449747 on 2010-11-17 上午12:03

  • How to catch exception in JSP????

    how to catch exception in JSP?
    I use JDeveloper 3.1
    I use connection with database .
    When I insert record in database
    when have duplicate of primary key
    how to catch this exception and
    back to previous page?
    I trying with folowing:
    <jsp:useBean id="RowEditor" class="oracle.jbo.html.databeans.EditCurrentRecord" scope="request">
    <% try {
    RowEditor.setUseJS(true);
    RowEditor.initialize(pageContext, "package2_Package2Module.Drzavi1View");
    RowEditor.setSubmitText("Save");
    RowEditor.setTargetUrl("Drzavi1View_SubmitInsertForm.jsp");
    RowEditor.createNewRow();
    RowEditor.setReleaseApplicationResources(true);
    RowEditor.render();
    catch(Exception e) {
    %>
    <script>
    alert("primary key duplication");
    history.back();
    </script>
    <% } %>
    but i't not working
    please help me

    i catch exceptions as you do, i don't have any problem...
    are you throwing the exception from your bean?
    actually i don't catch an Exception, but an SQLException...
    but it works... here is my code...
         try
    myclass.addElement(); // this is an insert into Oracle
    catch( DataBaseFailException e ) /// an exception that i throws inside after i receive an SQLException
              session.setAttribute("gMessage","e.getMessage()); // error code

  • Problem in catching Exception

    I am using servlets. In my program after a particular point I am not able to catch an Exception if it occurs.
    And after this point whatever Exception occurs that is not coming to catch block and its getting printed in webserver logs.
    Can someone help me
    Thanks

    Two possibilities:
    -First you might be catching checked exceptions but not unchecked exceptions. You can catch all types of exceptions by using a catch(Throwable) rather, or in addition to, a catch(Exception)
    -Second, you might be able to catch the exception at the top level and will have to instead add it to many of your methods instead. The reason is that your code might be called in an application server thread. And exceptions are not propogated out of a thread. But if you didn't create it you have no control over it. So your only choice is to add exception/thowable catches in many of your methods.

  • Cannot catch Exception thrown by ADF (source of exception is EJB)

    Even I tried to use try catch block, it still shows unwanted error popup (showing errors) automatically generated by adf.
    I know the source of this error is EJB, I try to insert duplicate field which must be unique. So EJB throws jdbc exception.
    How can I disable popup automatically generated by ADF and show my custom error text?
            try {
                BindingContainer bindings = getBindings();
                OperationBinding operationBinding = bindings.getOperationBinding("mergeCity");
                Object result = operationBinding.execute();   
                closePopup(popEdit);
                refreshTable();
                if (!operationBinding.getErrors().isEmpty()) {           
                    return null;
            } catch (Exception e) {
                System.out.println(".......... Error..........");
            }        Edited by: user12025867 on Oct 10, 2009 11:17 AM

    For custome error handling check this thread.
    Handling custom exceptions in 11g
    if you call this on button action, do not use partialSubmit that way when the page refreshes the popup will be gone automatically.

  • Catch exceptions that occur in the constructor of a managed bean

    Hello,
    I would like to catch exceptions that might occur in the constructor of a managed bean and redirect to an error page. My beans need to get data from a database and if the database is not accessible, an error page is to tell the user "try again later". I don't want to write an action or actionListener that is invoked by a button klick on the previous page to make error handling easier, because an actionListener should not know about the next page and what data the next page will need.
    I read all postings about this topic I could find in this forum. And there are three solutions I tried:
    1) register an error-page in web.xml
    Is there an example for using this in a JSF application? It did not work. I got a "Page not found" exception
    2) Use a phase listener. But how can a phase listener do this? Is there an example? I don't think it can do it in the beforePhase method because this method is called before the constructor of the managed bean is called.
    3) Use a custom ViewHandler. This is my renderView method which creates a "Page not found" Exception.
    public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException {
    ViewHandler outer = context.getApplication().getViewHandler();
    try {
    super.renderView(context, viewToRender);
    } catch (Exception e) {
    context.getExternalContext().redirect("/error.jspx");
    Several people write they've done it one or the other way. Please share your knowledge with us !!
    Regards,
    Mareike

    Hallo Mareike,
    Maybe I should abandon managed beans, create my own
    "unmanaged" ones inside of an action listener and put
    them somewhere my pages can find them.
    Its a pity, because I like the concept of managed
    beans.sure setter injection of JSF is fine!
    well workaround could be using <h:dataTable rendered="#bean.dbAccessible" ...>
    In your constructor you catch the exception and set
    dbAccessible = false;
    or you use error pages of webcontainer,
    but the pages couldn't contain JSF components, IMHO
    only plain JSP files.
    BTW perhaps somebody on MyFaces' list knows the solution:
    http://incubator.apache.org/myfaces/community/mailinglists.html
    Regards,
    Mareike-Matthias

  • Catching exception of a super constructor

    Is it possible to catch the exception thrown by a super class
    constructor in a sub clas constructor?
    public class A
         public A() throws Exception
              throw new Exception("Exception from A");
    class B extends A
         public B()
              try
                   super();
              catch(Exception e)
    }I get an error saying,
    A.java:16: call to super must be first statement in constructor
    super();
    ^
    Any thoughts?

    More on this here,
    http://archive.devx.com/free/tips/tipview.asp?content_i
    =2384&Java=ONThanks for that link. I completely agree to what it says.
    In other words, not being able to successfully construct our super class implies that we cannot create our derived class.
    But I feel this must be mentioned clearly somewhere in JLS. And the error message that we get must be "You cannot catch exceptions thrown by a super class constructor".

  • RFC Destination Catch Exceptions

    Hello,
    I've a program with call to RFC destination 'XI' , i want to know if it is possible catch exceptions when in the other system (XI) a fault occurs, for example, the database table in which I want to insert the data is not created. Now, if this happens a dump occurs
    thanks very much,

    Hello,
    You can try this way with your RFC function module:
    CALL FUNCTION 'RFC_WRITE_FILE'
        DESTINATION FP_P_DEST
        EXPORTING
          FILE                  = L_V_NAME
          FORMAT                = L_C_BIN
          SIZE                  = L_V_SIZE
          LANGUAGE              = SY-LANGU
        IMPORTING
          SIZE                  = L_V_SIZE
        TABLES
          FILEDATA              = L_IT_FILE
        EXCEPTIONS
          SYSTEM_FAILURE        = 1  MESSAGE L_V_RFC_MESS
          COMMUNICATION_FAILURE = 2  MESSAGE L_V_RFC_MESS
          ILLEGALNAME           = 3
          OTHERS                = 6.
      CASE SY-SUBRC.
        WHEN 0.
        WHEN 1.
        WHEN 2.
        WHEN 3.
        WHEN 6.
      ENDCASE.
    The SY-SUBRC value can be captured this way. Hope this helps.
    BR,
    Suhas
    Edited by: Suhas Saha on Mar 24, 2009 4:14 PM

Maybe you are looking for

  • Adobe Indesign CC 2014 crash on launch

    Hi I use this program as well as photoshop, illustrator and muse on a near-constant daily basis. Indesign has suddenly started crashing on launch - the rest of the apps still operate without issue. I've restarted, reinstalled indesign, disabled all f

  • Shared photo streams not working in new iPhoto?

    I upgraded to Mavericks and the new iPhoto to be able to work with the shared photo streams I'd created on my iPhone, but they seem to be nonfunctional in iPhoto 11. I'll select photos, create a stream, and add the photos; the pictures will say "adde

  • It's that time of the sea

    Time to spend money. I don't know what player I should buy. I tend to like Creative as a company so I believe my purchase for an MP3 player will be from them, but I'm willing to buy from another company if the player is good. I'm hoping to spend less

  • How to remove duplicates records from output ?

    how to remove duplicates records from output ?  i used delete adjacent but duplicates records are coming again ..suggest me

  • OSX mountain lion installation

    Ive downloaded OSX mountain lion but when I try to install it on my hard drive it tells me "this disc is used for Timed Backup" and doesn't let me select it. ?