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

Similar Messages

  • 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 catch exception from shared library on Linux?

    Description:
    JNI dynamically loads shared library. Shared library throws exception (class CTestException). JNI can not catch it by CTestException name, only (...) works.
    My config:
    Linux RH AS 4 (x86 64)
    gcc: 3.4.5
    glib: 2.2.5
    Java 1.5.0_06
    g++ compiler options for JNI and shared libraries:
    g++ -Wl,-E -fPIC -shared ...
    There are multiple bugs on Java bugs database regarding C++ ABI incompatibility between Java binaries and stdc++ libraries linked with native code. But I could not find any conclusions on these bugs. Only plans/suggestions to recompile Java on new gcc. These bugs were quite old (regarding Java 1.3, 1.4). Now 1.6 is available but still there is same incompatibility. Maybe I am missing something and there is a way to fix this problem? Like to use specific gcc/glib versions for compilation? How people solve such problems? Any help is appreciated.

    It isn't any different; the commands are the same. You can find the exp executable in tehe $ORACLE_HOME/bin directory.

  • 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 refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • 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

  • Killing an exec'ed process from another thread

    Hi all,
    I written an application that executes some external OS - processes. There is a dispatcher thread, that starts the execution threads for some jobs. Every execution thread creates a Processes by calling runtime.exec(), adds this object to a TreeMap ( member of the dispatcher ), creates two threads for reading the output of the process ( sdtout & stderr ) and calls p.waitFor(). From this moment this thread is blocked. After the process is done, the results will be processed by this thread etc. Now I want to go ahead and let the application user kill the process. For them I let the dispatcher - thread, that has also a reference to the executed process to call destroy of it if necessary during the execution thread is blocked by waitFor() and two output threads are reading stdout & stderr. The problem is however that destroy() - call from another thread doesn't kill the subprocess. The subprocess is running until it's done or terminated from out of jvm. Have you an idea or example?
    Thanks a lot & regards
    Alex

    >
    I know you have been discussing your problem is that
    you can't kill a "sleep" process. But just to be
    sure, I tested your description by one thread exec-ing
    a "not-sleep" program, and then another thread had no
    trouble killing it.
    I took your code and wrote a program around it such
    that
    Thread1 :
    - creates a Job (but not a "sleep" job); creates a
    JobMap ; puts Job in JobMap
    - starts Thread2 (passing it JobMap)
    - sleeps 15 seconds
    - calls Job.kill() (your method)
    Thread2 :
    - gets Job from JobMap
    - calls Job.execute() (your method)
    It's quick and dirty and sloppy, but it works. The
    result is when the kill takes place, the execute
    method (Thread2) wakes from its waitFor, and gets
    exitValue() = 1 for the Process.
    so,
    In order to kill the sleep process, which (according
    to BIJ) is not the Process that you have from exec
    call, maybe the only way to kill it is to get its PID
    an exec a "kill -9" on it, same as you said you had to
    do from the commandline. I don't know if you can get
    the PID, maybe you can get the exec-ed process to spit
    it onto stdout or stderr?
    (I am on win, not *nix, right now, so I am just
    throwing out a suggestion before bowing out of this
    discussion.)
    /MelHi Mel,
    yes, it should work right on windows because you created probably the shell by cmd /c or something like this. If you kill the cmd - process, everithing executed by the interpretter will be killed too. My application is running on Windows and unix. On unix I have to execute the process from a shell ( in my case it is the born shell ). The problem is however, that the born shell has another behaviour as cmd and doesn't die. Do you have an idea how to get the pid of the process started by sh without command line? To kill the processes from the command line is exactly what my customers do now. But they want to get "a better service" ...:-)
    Regards
    Alex

  • How to copy images from another MC in reversed order??

    Hi everyone,
    I'm new to AS3 and have been fighting and searching for a solution to this problem for a week now, and I'm VERY close!
    I crated a MC holding of a series of images (about 50) and I jump around in it using plenty AS3 scripts (most of which I don't fully understand yet, but I'm working on that to! )
    I had to find a way to "rewind" (= play backwards) the MC. Since there is a stop(); command in almost every frame, prevFrame does not work and if I put that in a loop, it goes WAY to fast (but worked).. So I could think of only one way...
    Create a new (reverserd) MC with the same image sequence ald reverse it manually and play that one.
    This all works fine (very proud of it ).
    Now my question:
    To get this to work for multiple image sequences, I have to load all images twice (once in MC_1 and again in MC_2 and select them and reverse them).
    Not a big one, unless you want to create MANY of those SWF's...
    Is it possible to load the 50 images of the first MC in reverse into the second MC dynamically? JUST the images, noting else.
    extra info: the MC_2 is already in the lib(empty) and placed on the stage.
    something like:
    var pointer:Number=1;
    for (var:i:Number=50;i>=0;i--) {
    get MC_1.picure(var);
    put it in MC_2.frame(pointer);
    pointer = pointer + 1;
    All help is welcome and please take into account that I have little experience and copy most of my scripting from people like you
    T.I.A.
    Melluw

    I tried your advice (thanks for that)
    The event I already have is the mouse leave
    I //-d out the part I removed (what did work)
    The code I ended up with is:
    function Start() {
    stage.addEventListener(Event.MOUSE_LEAVE, cursorHide);
    function cursorHide(evt:Event):void {
    var currFrame = MC_1.currentFrame;
    if (CCW == true) {  //it is true in this case
      movStart = (50 - currFrame);
    else {
      movStart = currFrame;
    if (movStart>25) {
      MC_1.prevFrame();
    // removed swapChildren(MC_1, MC_2); // This is the part I removed
    // removed MC_2.gotoAndPlay(movStart);
    else {
      MC_1.gotoAndPlay (movStart);
    And if I leave the stage on the part where movStart is indeed >25
    Nothing happens,
    So I guess this is not what you meant
    Subject: Action Script 3 how to copy images from another MC in reversed order??
    I cannot direct you in the loading of the images approach, it will be too complicated, and will probably not work anyways... when you move away from a frame that has dynamic content, you lose the content.  So basically, there is nothing practical in taking that approach.
    I do niot understand what the problem will be with the enterFrame/prevFrame approach. If everything you can do with the mouse is already used (which I doubt) by the first mc, then there is nothing else you can do with this file.  You probably just need to rethink your control scheme.  You should search Google for "AS3 slideshow tutorial", and to lighten up your design, add "XML" in that search.
    >

  • HT204350 Incorrect link to "OS X: How to migrate data from another Mac using Mountain Lion and earlier"

    Incorrect link to "OS X: How to migrate data from another Mac using Mountain Lion and earlier". Should be http://support.apple.com/kb/HT6025

    I think the OP is saying OS X: How to migrate data from another Mac using Mountain Lion and earlier (which should be a link to HT4889) just links back to OS X: How to migrate data from another Mac using Mavericks (HT5872).
    It does indeed do that, & HT4889 seems to be MIA.

  • How to view messages from another iPhone using your apple Id

    How to view messages from another iPhone using your apple Id

    Sign into iMessage using the same ID (in Settings>Messages>Send & Receive).  The other phone should then see your messages too.

  • Start timer from another thread

    I am working on a project which will receive command from telnet and start a timer.
    In the sock function, I use form reference to call timer.start(), but timer control cannot start Tick event:
    Here is code for sock functin after receive the command:
     static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
                switch (requestInfo.Key.ToUpper())
                    case ("START"):
                        session.Send(requestInfo.Body);
                        changetimer(1, requestInfo.Body);
    break;}}
    Here is the function to call timer start:
      static void changetimer(int action, string incomingmsg)
                //timer1.Start();
                Form1 frm = (Form1)Application.OpenForms["form1"];
                switch (action)
                    case 1:
                         frm.timer1.Start();
                         break;
                    case 2:
                        frm.timer1.Stop();
                        break;
    and this is timer tick :
    private void timer1_Tick(object sender, EventArgs e)
                TimeSpan result = TimeSpan.FromSeconds(second);
                string fromTimeString = result.ToString();
                label1.Text = fromTimeString;
                second = second + 1;

    You should start the timer on the UI thread. You could use the Invoke method to access a UI element from another thread:
    static void changetimer(int action, string incomingmsg)
    //timer1.Start();
    Form1 frm = (Form1)Application.OpenForms["form1"];
    switch (action)
    case 1:
    frm.Invoke(new Action(() => { frm.timer1.Start(); }));
    break;
    case 2:
    frm.Invoke(new Action(() => { frm.timer1.Stop(); }));
    break;
    Hope that helps.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • How I can backup from another Hard disk through my Macbook air?

    How I can backup datas from another external storage disk by using My Macbook Air?

    How I can backup from another hard disk through my Macbook air in Time Capsule?

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

  • 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

  • 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

Maybe you are looking for