Catching Exception in Parent Thread

Hi Pros,
I have a thread having try-catch block. Whatever exception I am catching into catch block should be thrown to be handled by Parent thread.
Is there any way to do this.
Thanks,
Abhijit

You can't literally throw to the parent thread per se, and the concept of doing so doesn't really make any sense. But using UncaughtExceptionHandler, you can give some control to the parent thread.
package scratch;
public class Uncaught {
  public static void main (String[] args) throws Exception {
    Thread t = new Thread(new MyRunnable());
    Thread.UncaughtExceptionHandler eh = new MyUEH ();
    t.setUncaughtExceptionHandler (eh);
    t.start();
  static class MyRunnable implements Runnable {
    @Override
    public void run () {
      System.out.println ("Thread name is: " + Thread.currentThread ().getName ());
      throw new RuntimeException("Can't catch me, I'm the gingerbread thread!");
  static class MyUEH implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException (final Thread t, final Throwable e) {
      System.err.println ("The uncaught exception stack trace for Thread " + t.getName() + " is: ");
      e.printStackTrace ();
}

Similar Messages

  • 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

  • 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).

  • Catching all possible exceptions in gui thread

    Hi,
    I have such a problem: I am developing Swing app and sometimes it crashes by throwing an Exception which I don't catch. The effect is that this exception prints stack trace on System.err but user is not notified and wonders what is happening... I would prefer to show custom ErrorDialog with stacktrace.
    I am searching for simple and effective way to catch every possible exception thrown from within any library. I think of a few ways from which everyone has some disadvantages.
    The ideal way would be replacing AWT event queue dispatcher so I could process every GUI event inside try { } catch (Exception e) {} block. That would be a good place to catch all exceptions. Unfortunately I don't know if it is possible.
    For now I am trying such a solution:
    I start background thread together with main app. Then I redirect System.err and System.out streams to PipedStream connected to this background thread. This thread can analyze anything that is going to System.err and maybe recognize potential exception stacktraces. Then it can notify main thread of an exception. But it is not ideal as I have to parse the stream and it can always be not ideal in exception recognition. And the code is quite costly.
    Do you have any ideas, had similar problems?

    But how can I cause GUI thread to run in my thread
    group? As I suppose GUI thread is started by JVM and
    is something separate from my code - I can get a
    reference to GUI thread but don't know how to
    manipulate or replace it...One alternative is to completely separate the GUI code from your code.
    Your code, which is wrapped in appropriate try/catch blocks, runs on its own thread and does its own processing. When it's done with that processing, it queues the results on the event thread for display. If an exception occurs during your processing, then you queue something that notifies the GUI.
    The simplest way to implement this is to spawn a new thread for each operation. The Runnable that you give to that thread looks like the following:
    public MyOperationClass implements Runnable
        public void run()
            try
                // do your exception-generating code here
                SwingUtilities.invokeLater( new MyGUIUpdateClass(param1, param2));
            catch (Exception e)
                SwingUtilities.invokeLater(new MyExceptionReporter(e));
    }This is only a bare-bones solution (and hasn't been compiled). Since it separates the GUI from actual processing, you'll probably want to display a wait cursor while the processing thread is doing its thing. You'll probably end up implementing a class that implements this pattern. You may also want to create a producer-consumer thread, so that the user won't invoke, say, a dozen different operations at once.
    However, this sort of code is absolutely essential to Swing programming. Most apps do extensive non-GUI processing, such as database queries. If you run such queries in the GUI thread, your GUI will freeze.
    Sun has named this pattern "SwingWorker", although I don't think they've fleshed it out very fully: http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

  • Exception catching in event processing thread

    Hello!
    How to catch exceptions occurring in event processing thread during repaints, mouse & keyboard event processing etc.? All uncatched exceptions displayed in screen but I need to write them in logfile.
    Anton

    Yes - push your own event processor on to the AWT event queue. See my replies at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=484167
    and
    http://forum.java.sun.com/thread.jsp?forum=57&thread=163020
    Although for two completely different purposes, this technique will also allow you to put your own try/catch around super.dispatchEvent()
    Hope that helps
    Tom

  • Can a parent thread kill a child thread?

    I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

    Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class ServerPing extends Thread {
      String [] args;
      public static void main(String[] args) throws Exception {
        ServerPing sp = new ServerPing(args);
        sp.start();
      ServerPing(String [] args) {
        this.args = args;
      public void run() {
        Pinger pinger = new Pinger(this);
        pinger.start();
        try {
          sleep(30000);
        catch (InterruptedException x) {
          System.exit(0); // this is ok. It means the pinger interrupted.
        System.out.println("TIMEOUT");
        System.exit(1);
    class Pinger extends Thread {
      Thread p = null;
      Pinger (Thread p) {
        this.p = p;
      public void run() {
        try {
          URL simpleURL = new URL("http://localhost:7001/ping.jsp");
          BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
          String inputLine;
          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          p.interrupt();   // <<-- interrupt the parent
        catch (Exception x) {
          x.printStackTrace();
    }

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • 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.

  • Exceptions thrown in Thread Constructors

    Hi,
    Im having a problem with exceptions been thrown during thread constructors... mainly that when it happens, the JVM still seems to track the dud thread as an active thread (See example code below).
    As you can see, the thread throws an exception during creation, and hence never gets created as such (mt stays null). Yet Thread.activeCount() reports that its still hanging around somewhere, yet it cant be referenced. Unfortunately this is resulting in me getting a rather large buildup of these duds, as its part of a "retry" phase in my software.
    Any thoughts/comments/suggestions?
    Thanks,
    Roger.
    import java.net.Socket;
    public class myMain
        public myMain()
            myThread mt=null;
            while (true) try
                System.out.println(Thread.activeCount());
                Thread.sleep(100);
                mt = new myThread();
            catch (Exception ex)
                System.out.println(mt);
                System.err.println(ex);
        public static void main (String[] args)
            new myMain();
    public class myThread extends Thread
        public myThread() throws Exception
            throw new Exception();
    }

    It's not hard to obtain this reference (for instance we can catch exception in the constructor and do something before rethrowing it) - but what can we do with this reference? There's no way to destroy the thread object save starting it. But this is really ugly (but works):
    public class NewThreadException {
         public static class myThread extends Thread {
              protected boolean stillborn;
             public myThread() throws Exception
                  super(new ThreadGroup("My Group"), "My Thread");
                  try {
                      throw new Exception();
                  } catch (Exception e) {
                       stillborn=true;
                       start();
                       throw e;
             public void run() {
                  if (stillborn) return;
         public static void main(String[] args) {
            myThread mt=null;
            while (true) try
                System.out.println(Thread.activeCount());
                Thread.sleep(100);
                mt = new myThread();
            catch (Exception ex)
                System.out.println(mt);
                System.err.println(ex);
    }BTW there's already one private stillborn in Thread class itself.

  • 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.

  • Catching exception from inherited constructor

    Hi all,
    If I'm extending a class and the constructor of the parent class throws an exception, is there any way to catch that exception in my constructor? What I would like to do is something like this.
    public class MyClass extends OtherClass {    // the constructor for OtherClass throws an exception
        public MyClass() {
            try {
                super();
            } catch (Exception e) {}
    }But of course you can't do that because super() has to be the first command in the method. Is there any other way to accomplish this? My objective is to chain this exception to a different type of exception.

    Write a factory method? For example:
    class ABCException extends Exception {}
    class XYZException extends Exception {}
    class OtherClass {
        public OtherClass()  throws ABCException {
            throw new ABCException();
    class MyClass extends OtherClass {    // the constructor for OtherClass throws an exception
        protected MyClass() throws ABCException {
           super();
        public static MyClass instance() throws XYZException {
            try {
                return new MyClass();
            } catch (ABCException e) {
                throw new XYZException();
    }

  • Exceptions in child thread

    Hello,
    I am writing a few classes that i plan on reusing a lot. The classes create
    child threads that do ... work. If a exception is cought in one of the child threads
    I want to send it up to the caller. I can't declare the run() method of a thread to throw
    an exception ... so could someone suggest a nice clean way to get the cought exception back to the caller.
    Thanks,
    jd

    To answer that question, you need to think about what the "caller" (the parent thread) is doing while the child thread is executing.
    Is it waiting in a join() call?
    Is it doing its own processing?
    What do you expect it to do when a child thread throws an exception?
    (The answer to the bolded questions may drive how you report the exception back to the parent thread.)
    With a typical single-threaded chain of calls, when an exception is encountered, there is a well defined stack back to the main() method--main called foo which called bar which called baz, etc. In a multithreaded context, the parent thread could potentially be executing any of its instructions when the exception occurs. Remember, the parent thread and child thread are executing independently of each other.

  • Doubt on try/catch exception object

    why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
    btw, i was just go through duke stars how it works and saw this
    http://developers.sun.com/forums/top_10.jsp
    Congrats!

    Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
    If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
    Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
    That's why exceptions are treated differently from runtime errors.

  • How to not stop in catched exception in jdb

    Hi,
    I am not sure if this is a silly question :-)
    When I use jdb to debug a kvm.
    It always stop in catched exceptions which I don't care.
    How to not stop in catched exception?
    Thanks for suggestions
    gan

    for example
    my jdb stop and show:
    vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    Exception occurred: java.lang.NumberFormatException
    (to be caught at: com.sun.midp.main.Configuration.getIntProperty(), line=144, bci=28)
    thread="Thread1", java.lang.Integer.parseInt(), line=273, bci=11
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    I input
    ignore java.lang.NumberFormatException
    in jdb and run again, but jdb still stop
    What is the right usage of ignore in jdb?
    Thanks for any suggetion or comment.
    gan

Maybe you are looking for

  • Invalid path in OBIEE 11.1.1.5

    Hi, I have intergrated with OBIEE 11.1.1.5 with portal.While viewing the reports a particular report throws an error Error: Dashboard Display Error       Invalid path () -- path not found in dashboard Error Details: Error Codes: QM3V3HLV Can you some

  • How do I make the photos on my external hard drive appear in the iPhoto screen

    I recently had my hard drive "wiped" at the Apple store to speed it up. In the process I lost a lot which I am now restoring. Prior to the wipe the photos stored in my EHD appeared in the iPhoto screen by default. I have lost that and don't know how

  • My Album Art is not Appearing

    This has been a problem for me for a very long time. That Everytime i'm transfering music to my ipod touch 4th Gen. I've tried restoring my ipod, uninstalling itunes and reinstalling. Nothing seems to be fixing the problema and it's starting to get a

  • Control Record - Data fetch in IDOC

    Hi Folks, Can you please tell me from where the Control Record data for ORDERS and ORDCHG gets populated. ? I have checked the FM - IDOC_OUTPUT_ORDERS which has one of the import parameters as control_record_in which is already populated when it reac

  • RAM & HDD Upgrading

    Hi, I'm fairly tech obsessed and am fairly proficient with computers in general, but I've only had real experience playing around with PCs in general. I'm seriously considering purchasing a Mac-Book and was just wondering how easy it was to manually