How to throw exception in run() method of Runnable?

Hi, everyone:
I want to know how to throw exception in run() method of interface Runnable. Since there is no throwable exception declared in run() method of interface Runnable in Java API specification.
Thanks in advance,
George

Thanks, jfbriere.
I must add though that if your run() methodis
executed after a call to Thread.start(), then
it is not a good choice to throw anyRuntimeException
from the run() method.
The reason is that the thrown exception won't be
handled appropriately by a try-catch block.Why do you say that "the thrown exception won't be
handled appropriately by a try-catch block"? Can you
explain it in more detail?
regards,
George
Because the other thread runs concurrently with and independently of the parent thread, there's no way you can write a try/catch that will handle the new thread's exception: try {
    myThread.start();
catch (TheExceptionYouWantToThrowFromRun exc) {
    handle it
do the next thing This won't work because the parent thread just continues on after myThread.start(). Start() doesn't throw the exception--run() does. And our parent thread here has lost touch with the child thread--it just moves on to "do the next thing."
Now, you can do some exception handling with ThreadGroup and uncaughtException(), but make sure you understand why the above won't work, in case that was what you were planning to do.

Similar Messages

  • Is it possible to throw an exception from run method of a thread?

    Is it possible to throw an exception from "run method of a thread"(implemented as runnable implementation)?
    Is it advisable to do so?

    Is it possible to throw an exception from "run method
    of a thread"(implemented as runnable
    implementation)?Yes, an unchecked one. Runtime exceptions.
    Is it advisable to do so?If you mess up it happens automatically. But basically: no.

  • Web part throwing exception at run time but not in debug mode

    The below code is throwing exception at run time but does not throw exception while debugging in Visual Studio. This is really causing difficulty for me to detect the cause of exception. Below I have also placed the exception image for reference.
    namespace CheckforContractorLogin.VisualWebPart1
    public partial class VisualWebPart1UserControl : UserControl
    protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
    string loginName = string.Empty;
    string coc_url = string.Empty;
    SPQuery spQuery = new SPQuery();
    spQuery.Query = "<Where><Eq><FieldRef Name='LoginName' /><Value Type='Text'>" + currentUser + "</Value></Eq></Where>";
    Guid _spSiteID = SPContext.Current.Site.ID;
    Guid _spWebID = SPContext.Current.Site.OpenWeb().ID;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite _spSite = new SPSite(_spSiteID))
    using (SPWeb _spWeb = _spSite.OpenWeb(_spWebID))
    //if user has already accepted the COC
    SPList getSPList = _spWeb.Lists["RedirectUrl"];
    SPListItemCollection getspItemColl = getSPList.Items;
    foreach (SPListItem item in getspItemColl)
    if (Convert.ToString(item["Title"]) == "Policy Acceptance")
    coc_url = Convert.ToString(item["Url"]);
    SPList spList = _spWeb.Lists["Policy Acceptance Status"];
    SPListItemCollection spItemColl = spList.GetItems(spQuery);
    bool result = getADUserInfo();
    if ((spItemColl.Count == 0) && (result))
    Response.Redirect(coc_url);
    protected string currentUser
    get
    string currentUser1 = HttpContext.Current.User.Identity.ToString();
    int index = currentUser1.IndexOf("\\") + 1;
    string currentLoginUser = currentUser1.Substring(index);
    return currentLoginUser;
    protected bool getADUserInfo()
    DirectoryEntry dentry = null;
    DirectorySearcher dsearcher = null;
    string ldap = string.Empty;
    string empID = string.Empty;
    string _empID = string.Empty;
    try
    Guid spSiteGUID = SPContext.Current.Site.ID;
    Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
    using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
    SPList spList = elevatedWeb.Lists["LDAP_Paths"];
    SPQuery spQuery = new SPQuery();
    spQuery.Query = "<Where><Eq><FieldRef Name='OU'/>"
    + "<Value Type='Text'>QD</Value></Eq></Where>";
    SPListItem spItem = spList.GetItemById(1);
    ldap = spItem["Path"].ToString();
    dentry = new DirectoryEntry();
    dentry.Path = ldap;
    dentry.Username = "******\\sp_admin";
    dentry.Password = "******";
    dsearcher = new DirectorySearcher(dentry);
    dsearcher.Filter = String.Format("(&(ObjectCategory=Person)(sAMAccountName=" + currentUser + "))");
    SearchResult searchResult = dsearcher.FindOne();
    dentry = searchResult.GetDirectoryEntry();
    if (searchResult != null)
    if (dentry.Properties.Contains("physicalDeliveryOfficeName"))
    empID = dentry.Properties["physicalDeliveryOfficeName"][0].ToString();
    if (empID.Contains("QA-"))
    return true;
    else
    return false;
    catch (Exception e)
    throw e;
    finally
    dentry.Close();
    dentry.Dispose();
    dsearcher.Dispose();

    Hi Zakir,
    I am not sure but it would be nice if you can do following
    Try search ULS log with correlation id and find exact error and share here. If not able to find do following
    Or in catch block write
    Response.Write(ex.ToString());
    and check what exception its giving.

  • How to throw Exception in Thread.run() method

    I want to throw exception in Thread.run() method. How can I do that ?
    If I try to compile the Code given below, it does not allow me to compile :
    public class ThreadTest {
         public static void main(String[] args) {
         ThreadTest.DyingThread t = new DyingThread();
         t.start();
         static class DyingThread extends Thread {
         public void run() {
         try {
                   //some code that may throw some exception here
              } catch (Exception e) {
              throw e;//Want to throw(pass) exception to caller
    }

    (a) in JDK 1.4+, wrap your exception in RuntimeException:
    catch (Exception e)
    throw new RuntimeException(e);
    [this exception will be caught by ThreadGroup.uncaughtException() of this thread's parent thread group]
    In earlier JDKs, use your own wrapping unchecked exception class.
    (b) if you know what you are doing, you can make any Java method throw any exception using Thread.stop(Throwable) regardless of what it declares in its "throws" declaration.

  • How to throw exception from Listener's Event Methods

    Hi,
    We are using Jdev 10.1.3 and I'm implementing a class that implements EntityListener and RowSetListener interfaces.
    The problem that i'm facing is when I override the event methods of the interface (Which don,t throw any exception) , I'm not able to throw any exceptions in overridden methods also. Kidnly guide me on how to achieve this...
    Sample Code :
    public class GenericHistoryViewObjectImpl extends ViewObjectImpl implements RowSetListener
    // this event is fired when a row is deleted from rowset and it registers data in history
    public void rowDeleted(DeleteEvent event)
    latestEvent = "DEL";
    try
    GenericHistoryManager.registerDataInHistory(this);
    wasLastEventExecutedSuccessfully = 1;
    catch (Exception e)
    e.printStackTrace();
    wasLastEventExecutedSuccessfully = 0;
    genericHistViewException = e;
    from The mothod public void rowDeleted(DeleteEvent event) of RowSetListener i want to throw an exception ...

    JSalonen is totally correct. I would only add that this topic, generally, exposes the differences between checked and unchecked exceptions. Unchecked exceptions extend RuntimeException or Error. Checked exceptions extend Throwable or Exception. There are important differences.
    Checked exceptions must specifically be caught or declared in a throws clause of a caller. Unchecked exceptions do not have this restriction. This means you can always 'wrap' (or throw without wrapping) an unchecked exception. Unchecked exceptions are very useful. You can use an existing unchecked exception, or create your own by extending RuntimeException or Error.
    To illustrate the difference, let's say we are creating a new user account and storing it in the database. For a checked exception, I might define DuplicateUserRegistration in case a user registers with an existing user name (a non-fatal error case that can be anticipated in system design). However, if the database was down, I would not throw SQLException (which is checked) but rather something like ResourceUnavailableError. This would be unchecked. A calling class (normally) will not be able to realistically handle a situation where the database is down, so why force that caller to either declare throws SQLException or catch SQLException for this instance?
    - Saish

  • How to throw exception..?

    class A
    void execute() throws Exception
    int i=10/0;
    public static void main(String args[])
    try
      new A().execute();
    catch(Exception e)
    System.out.println(e);
    (or)
    class A
    void execute() throws Exception
    try
    int i=10/0;
    catch(Exception e)
    throw e;
    public static void main(String args[])
    try
      new A().execute();
    catch(Exception e)
    System.out.println(e);
    }hi i want to knw which form of throwing of exception is best from the above two program... and also tell me the reason pls... can anyone give the solution.....

    There are two general classes of exceptions in java, often called checked and unchecked.
    The exception thrown by zero divide, in your example, is a RuntimeException and doesn't require a throws clause.
    Most exceptions are throw with a throw statement, but a few kinds are throw directly by the JVM, zero divide or NullPointerExceptions being examples.
    If you need to throw an exception you typically create an exception class of your own, by extending the Exception class. That way you can have a catch clause that catches just that one kind of exception and your program can act accordingly.

  • How to throws exception from subprocess?

    Hi,
    I use subprocess in my process and I need throws exception from subprocess to my main process.
    Thanks for help.
    Jakub

    The only to throw an exception from a sub process is by leveraging the Exception event (from the event view).
    You need to throw the exception, by dragging the Exception event and choose Throw into your subprocess. Then you need to add an exception "catcher" in the parent process to catch the Exception.
    Jasmin

  • How to raise exception in bor method without showing runtime error

    I want to raise custom exception in the bor method like below. However, it will show runtime error when executing codes below. Any knows how to raise custom exception in the bor method without runtime error?
    raise 9021.

    Hi Nick
    You need to define the exception 9021 for the method and then you use the macro EXIT_RETURN as below
    exit_return 9021 sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    Regards
    Ravi

  • Throws Exception

    Dear Expert,
    May I know how to throw Exception from a thread back to calling program ?
    As I always get the following message when compiling the code
    cannot override run() in java.lang.Thread; overridden method does not throw java.lang.Exception public void run() throws Exception
    Thanks!
    w

    From what I can see in the javadoc, you can create a subclass of ThreadGroup and override its uncaughtException method, then you'd have to create a Thread that belongs to an instance of your ThreadGroup subclass and have its overridden method set some variable in your main thread. However you should recognize that whatever started your thread may not even exist when it throws that exception, and it may not be sitting around waiting for your thread to throw an exception. You should reconsider that requirement carefully before actually trying to implement it.

  • Throws Exception - a newcomer...

    I have written a small amount of code that takes information from a text file and displays it in a GUI (swing) - this is called my RasterDisplay class. However, I am now creating another part of the GUI which will have a button that makes a new RasterDisplay. However, when I try and call my RasterDisplay constructor from within my actionPerformed method (see below) It tells me I have an "unhandled Exception type Exception". I can't throw Exception in the actionPerformed method so how do I get this method to work? Any help would be greatly appreciated - I am a total newcomer to Java and can't make head nor tail of related topics in all the forums...
    Cheers!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    public class RasterToolbar extends JFrame implements ActionListener{
         JButton open;
         public static void main(String[] args) throws Exception{
              new RasterToolbar();
         //method to make display panel with buttons
         public RasterToolbar()throws Exception{
                   super("Raster Viewer 1.0 beta");
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                   Container contentPane = getContentPane();
                   JPanel p1 = new JPanel();
                   p1.setLayout(new FlowLayout());
                   p1.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
                   open = new JButton("Open Viewer");
                   p1.add(open);
                   contentPane.add(p1,BorderLayout.WEST);
                   open.addActionListener(this);
                   pack();
                   setVisible(true);
         public void actionPerformed(ActionEvent ev){
         if(ev.getSource()== open){
              System.out.println("Open pressed");
              RasterDisplay viewer = new RasterDisplay(); // HERE IS THE PROBLEM LINE!
    }

    public void actionPerformed(ActionEvent ev){
         if(ev.getSource()== open){
              System.out.println("Open pressed");
              try {
                   RasterDisplay viewer = new RasterDisplay(); // HERE IS THE PROBLEM LINE!
              } catch(Exception e) {
                   // do what ever you want here!
                   e.printStackTrace();
    }

  • Java_Tool to find throwed Exceptions

    Hi all,
    this is an example code:
    public class SuperException extends Exception {...}
    public class SubException1 extends SuperException {...}
    public class SubException2 extends SuperException {...}
    public void method1() throws SuperException {
    try {
    //an invocation
    method2();
    catch (Exeption e){
    throw new SubException1();
    public void method2() throws SuperException {
    try {
    catch (Exeption e){
    throw new SubException2();
    I'm looking for a tool, which lists all throwed Exceptions in a method and possible in all invocation methods of this method.
    In this case, the result of tool for method1 should be a list of Exceptions (SuperException, SubException1 and SubException2). And for method2 are only SuperException and SubException2 issued.
    Thanks for help,
    Cuong.

    http://www.cs.ubc.ca/~mrobilla/jex/thanks a lot. It seems to be a tool, which I looked for. But I cannot launch it. I tried to do the example. But it failed by generating the stubs with the following error:
    Generating stubs...Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.lang
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at ca.ubc.cs.jex.stubs.BasicExtractor.getClasses(Unknown Source)
    at ca.ubc.cs.jex.stubs.BasicExtractor.generateJexFiles(Unknown Source)
    at at.dms.kjc.Main.generateStubs(Unknown Source)
    at at.dms.kjc.Main.run(Unknown Source)
    at at.dms.kjc.Main.main(Unknown Source)
    at ca.ubc.cs.jex.Jex.main(Unknown Source)
    Can you tell me why?
    Otherwise, I received jex-files, in which no exception is appeared. When should exceptions be returned in jex file?

  • How to get value from Thread Run Method

    I want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that it seems that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    /* I should get Inside the run method::: But I get only Inside */
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";

    I think this is what you're looking for. I hold up main(), waiting for the results to be concatenated to the String.
    public class sampsynch
        class SampleThread extends Thread
         String x = "Inside";
         public void run() {
             x+="the run method";
             synchronized(this) {
              notify();
        public static void main(String[] args) throws InterruptedException {
         SampleThread t = new sampsynch().new SampleThread();
         t.start();
         synchronized(t) {
             t.wait();
         System.out.println(t.x);
    }

  • Error on /SafeMode: error while trying to run project uncaught exception thrown by method called

    i try run VS 2012 with /SafeMode. I create new empty Winform. When I start debug, I got:
    "error while trying to run project uncaught exception thrown by method called through reflection"

    Hi Matanya Zac,
    Did you restart your machine? How about installing the VS2012 update 4?
    >>error while trying to run project uncaught exception thrown by method
    Did you install the VS update in your VS IDE? I met this issue before which was related to the VS update:
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/5ead8ee9-ea09-4060-88b0-ee2e2044ff82/error-while-trying-to-run-a-project-uncaught-exception-thrown-by-method-called-through-reflection?forum=vsdebug
    If still no help, I suggest you repair your VS, and then restart your machine, test the result.
    Best Regards,
    Jack
    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.

  • How to Throw/Catch Exceptions in BPM

    Hi All,
    I've seen a couple articles that talk about how to Throw/Catch an execption in a BPM. My question has two parts:
    1) RFC Call: I was able to catch an Fault Message in an exception step when calling an RFC (Synchronous Interface). What I wanted to do is use the fault message (exception) and store it in a DB for later review.
    2) IDOC: I'm sending an IDOC to R3 from a BPM. The send step is enclosed in a block w/ an exception. The send step is throwing an error (IDOC adpater system error), but the exception is never thrown. My question is: when the error occurrs at the adapter level does it still throw an exception in a BPM?
    Thanks for any tip/advice/anything!
    Fernando.

    Hi Fernando,
    1) Define a send step in the exception branch.
    2) If u send a IDoc from R/3 to XI and the IDoc adapter is running to an error of course there cant be an exception in ur business process. Usually the IDoc adapter sends back status back up via ALEAUD. In case of success IDoc should have then '03', if the adapter cannot send anything the IDoc should remain at '39'. U should send a ALEAUD in case of exception of BPM switching to status '40', in case of success to '41'.
    Regards, Udo

  • How to handle exception thrown in standard bo method in the workflow design

    Hi Experts
        how to handle exception thrown from standard bo method in the workflow design. For example, bo BUS2032, METHOD confirm. If the user cancel it, it will throw exception. In the workflow, how to catch this exception and add corresponding steps in the workflow.

    @jrockman li
    Try to implement the logic that what ever you are performing in the BO mehtod in a FM and in the FM you have tab with name EXECPTIONS define the execption in that tab.Now in the BO method you call this FM  and if the exception occurs by using RAISE you can raise the exception in the FM and based on the number of exceptions your sy-subrc value will be set
    so when sys-subrc is not eq 0 then pass a value back t the workflow container., I think this will work.
    a sample Snippet for understanding purpose
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
        filename         = <path>
        filetype         = 'ASC'
      IMPORTING
        filelength       = lv_len
      TABLES
        data_tab         = l_txt_tab
      EXCEPTIONS
        file_write_error = 1          " If this Exception occurs
        invalid_type     = 2
        no_authority     = 3
        unknown_error    = 4
        OTHERS           = 10.
    CASE sy-subrc.
      WHEN 1. " SY-SUBRC value will be 1 then,
          " Pass or set the value back to the workflow conatiner element
    ENDCASE.

Maybe you are looking for

  • Airport Express and Brother HL-2040 printer from Windows

    Hi all, I'm installing an Airport Extreme network at home in order to share a printer. We have both macs and windows xp pcs. From my macBook no problems, I can see the printer and print. The problem comes with Windows XP: I can add the printer using

  • Is there any way to convert recorded actions into JSX Javascript file?

    For photoshop, there's http://ps-scripts.sourceforge.net/xtools.html (scroll down to "ActionFileToJavascript") which can convert recorded photoshop actions into jsx. Is there any such resource for Illustrator?

  • Archive & Install on an upgrade machine

    I have a MacBook where I chose the upgrade options. It runs slow and is buggy. I have a Mac Pro I did an Archive & Install and Leopard works great. Can I stick the DVD back into my MacBook and do an Archive & Install to get a fresh load?

  • What is the use of CM relevance field in DMS ?

    Hi DMS gurus, What is the use CM relevance field in DMS ? Is there any specific scenario ? Regards, Sunny

  • Change date for Leave of absence

    Hi, We have the following scenario in our ESS form-- When an employee uses Portal form for changing the Absence date ( i.e change date after it has been approved or rejected )for the Absence Type LOA . The Manager who receives the work item should ge