Throw exceptions from threads?

Is it possible to throw exceptions from threads since I can't add the throws statement to the run method I don't know how I could do it...
Any help greatly appriciated!
Cya

Is it possible to throw exceptions from threads since
I can't add the throws statement to the run method I
don't know how I could do it...
Any help greatly appriciated!
CyaYou can't throw checked exceptions, because obviously the code responsible for invoking the run() method wouldn't know what to do with it, and you wouldn't be the one to catch them. You can however throw unchecked exceptions (such as those based on RuntimeException).

Similar Messages

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

  • Keytool throwing  Exception in thread "main" java.lang.OutOfMemoryError:

    Hello all.
    I am unable to run keytool as it throws the following error. I am running Vista(x86),JDK 1.6 with a system with 4G of ram.
    Any idea's how i would solve this? I have tried installing other JDK's with the same results.
    Thanks in advance.
    C:\Users\Gav>"c:\Program Files\Java\jdk1.6.0_07\bin"\keytool -genkey -alias andr
    oiddebugkey -keyalg RSA -validity 365 -keypass android -keystore debug.keystore
    -storepass android
    What is your first and last name?
      [Unknown]:  a
    What is the name of your organizational unit?
      [Unknown]:  b
    What is the name of your organization?
      [Unknown]:  c
    What is the name of your City or Locality?
      [Unknown]:  d
    What is the name of your State or Province?
      [Unknown]:  e
    What is the two-letter country code for this unit?
      [Unknown]:  fs
    Is CN=a, OU=b, O=c, L=d, ST=e, C=fs correct?
      [no]:  yes
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
            at java.io.WinNTFileSystem.list(Native Method)
            at java.io.File.list(File.java:973)
            at sun.security.provider.SeedGenerator$1.run(SeedGenerator.java:166)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.security.provider.SeedGenerator.getSystemEntropy(SeedGenerator.java:146)
            at sun.security.provider.SecureRandom.engineNextBytes(SecureRandom.java:170)
            at java.security.SecureRandom.nextBytes(SecureRandom.java:433)
            at java.math.BigInteger.randomBits(BigInteger.java:475)
            at java.math.BigInteger.<init>(BigInteger.java:464)
            at java.math.BigInteger.largePrime(BigInteger.java:596)
            at java.math.BigInteger.probablePrime(BigInteger.java:538)
            at sun.security.rsa.RSAKeyPairGenerator.generateKeyPair(RSAKeyPairGenerator.java:105)
            at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:656)
            at sun.security.x509.CertAndKeyGen.generate(CertAndKeyGen.java:131)
            at sun.security.tools.KeyTool.doGenKeyPair(KeyTool.java:1156)
            at sun.security.tools.KeyTool.doCommands(KeyTool.java:786)
            at sun.security.tools.KeyTool.run(KeyTool.java:172)
            at sun.security.tools.KeyTool.main(KeyTool.java:166)

    See http://bugs.sun.com/bugdatabase/view_bug.do;?bug_id=6474350
    It seems that one way used by SecureRandom to gather entropy is to scan the directory pointed at by java.io.tmpdir. If it is very full, it runs out of memory. Clean you Local Settings\Temp directory.

  • I can throw exception from a catch

    Hello,
    I have created a new Exception : myException (for example).
    and, i can't throw it under a catch bloc !!
    My code :
    public myMethod( ... ) throw myException {
         try {
              if(true) thorw new NullPointerException("test nll pt");
         } catch(NullPointerException nullPt) {
              if(true) throw new myException("toto",nullPt.getMessage());
    this code doesn't want to throw "myException" from the "catch" !
    Why ?
    myException extends the class Exception.
    Thanks.
    maxx.

    First, I assume you didn't cut and paste the code, as what you have there won't compile. Can you 1) paste the actual code and 2) be a bit more specific about what's happening?
    Aside from a couple of misspellings, I don't see why it wouldn't throw myException. Is it not compiling? Running but not throwing any exception? Throwing a different exception?

  • Throwing exceptions from Java Stored Procs

    Hi,
    We'd like to be able to define our own exceptions from our Java Stored Procedures (i'm going to call them JSP's even thought that's not PC). I am aware that the manual says "When a Java stored procedure executes a SQL statement, any exception thrown is materialized to the procedure as a subclass of java.sql.SQLexception. That class has the methods getErrorCode() and getMessage(), which return the Oracle error code and message, respectively."
    Does this mean that we can't really extend the SQLException class and define our own set of methods for handling exceptions in JSP's? Is there a work around for handling exceptions in JSP's? Since exception handling is such a powerful component of Java, I figure someone has addressed the limitations of the above paragraph.
    Thanks,
    Kristi
    null

    Unfortunately, right now GCC's standard C++ runtime library is NOT threadsafe. You can find documentation supporting this on the GCC website. Since you're running a multithreaded Java/JNI application, you'll certainly hit this shortcoming.
    <p>
    Supposedly, this will all be fixed in GCC 3.0.
    <p>
    In the meantime, if you're using SPARC, the only option you have is either using SC4.2 or Forte 6 Update 2 (this particular version is VERY important for several reasons).

  • Throwing Exceptions from a new Thread

    Please help if you can.........
    I have a very simple RMI server, that is used to run processes in seperate threads on a server machine, that are kicked off by a client GUI.
    All works fine, except if the process can not be found, then the server generates an IOException. How can I get the thread to throw the exception back to the RMI Server, and then back to the GUI.
    I have tried to throw Runtime Exceptions but that did not work, and I can not declare the run method of the thread to throw a remote exception......
    Any help would be most appriciated...
    G

    /* the listener interface */
    public interface ExceptionListener {
      void exceptionOccured(Throwable t);
    /* the runnable object */
    public class WorkerThread implements Runnable {
      List exceptionListenerList;
      public void addExceptionListener(ExceptionListener l) {
        exceptionListenerList(l);
      public void run() {
        try {
        // do the work, e.g some JDBC stuff
        } catch(Throwable t) {
          // error occured, first do some logging, then notify all listeners
          t.printStackTrace();
          for(i=0; i<exceptionListenerList; i++) {
            (ExceptionListener)exceptionListenerList.get(i).exceptionOccured(t);
    /* this clas creates and & runs the thread; before doing this it
    registers itself as an ExceptionListener to the runnable object */
    public class ThreadStarter implements ExceptionListener {
      public final void exceptionOccured(Throwable t) {
        // do whatever you want to do with the exception
      public final void startThread() {
        WorkerThread wt = WorkerThread();
        wt.addExceptionListener(this);
        new Thread(wt).start();
    }By the way: I "borrowed" the ExceptionListener / ExceptionCallback idea from the book "java thread programming - the authorative solution" by paul hyde.

  • IViews throwing exception from Non Admin Login?

    Hi,
    I have created some iViews using .Net PDK for SAP.
    I have added these iViews to a page. Then the page is added to workset. I have created a new role and assigned this workset to the new Role. Then I have created a new User and associated this user with the newly created Role.
    Now the problem is whenever I login to portal using new user name and password I am able to see the workset as well as page and iViews. But these iViews are throwing following exception.
    An Error occurred while processing one of the iViews on this page in the .NET server.
    More information:
    1. Default Trace
    Exception id: 10:37_04/10/05_0037_6409650
    However these iViews are running properly when I preview them from admin login.
    What are possible causes/solutions for the above mentioned behavior?
    Thanks for suggestions
    Regards,
    Vikas Khandpur

    Hi Vikas
    You should use the Permission Editor to assign user, group and role permissions to portal objects.
    You can launch the Permission Editor in two ways:
    1. Using the central Permission Editor
    a. Choose System Administration ® Permissions.
    b. Locate the folder or object you want to assign or edit permissions for, right-click it and choose Open ® Permissions from the context menu.
    2. Using the object-specific Permission Editor
    a. Launch the relevant administration tool or editor in the portal.
    b. In the Portal Catalog, locate the object or folder to want to set or edit permissions for. Then, do one of the following:
       i. Right-click the object and choose Open ® Permissions from the context menu.
       ii. Open the object in the editor, and from the Display menu or drop-down list, choose Permissions.
    To know how to set permissions in the permission editor, please refer to the following thread.
    http://help.sap.com/saphelp_nw04/helpdata/en/f6/2604db05fd11d7b84200047582c9f7/content.htm
    As for your doubt on why you are able to view the iViews from an administrator's login,it is because The standard super administer role is assigned maximum access to the entire set of portal initial content. The Super Administrator role is assigned by default to the Administrators group. Therefore, initially all standard administrator users have super administrator permissions in the portal.
    Hope that helped.
    Best Regards
    Priya

  • Throwing Exceptions from CacheStore

    If I encounter an exception whilst persisting a cache's contents via a CacheStore implementation, how can I pass this expection up to the code that put the entry on the cache? If it doesn't make it into the database, I'd like to throw something to let the client code know.

    Hi Mike,
         Rethrowing synchronous CacheStore exceptions to the calling thread is now supported in Coherence 3.0. To do so, set the <tt>rollback-cachestore-failures</tt> configuration element in your <tt>read-write-backing-map-scheme</tt> or <tt>versioned-backing-map-scheme</tt> caching scheme to true.
         Jason

  • Collecting Exceptions from Threads in ThreadPoolExecutor

    Hi,
    I have a scenario where I am using a thread pool executor to submit threads. and then, I am waiting at the end for all threads to finish using below code.
    threadPoolExecutor.shutdown();
    try {
    while (!threadPoolExecutor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
    // awaiting termination of all the threads here.
    What I required is, I want to catch the exceptions that are been thrown by one of the threads in ThreadPoolExecutor in my method where I am submitting threads and want to do some processing based on those exceptions.
    Is it possible to catch those exceptions that are been thrown by the threads in ThreadPoolExecutor? If so, can some one please let me know how to do that?
    Thanks
    Pallavi
    Here is sample code:
    import java.io.IOException;
    import java.util.concurrent.Callable;
    import java.util.concurrent.Future;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    public class sample2 { 
    ThreadPoolExecutor threadPoolExecutor = null;
    public sample2()
    super();
    threadPoolExecutor = new ThreadPoolExecutor(5,10,5,TimeUnit.MINUTES, new ArrayBlockingQueue(10));
    public static void main(String[] args) throws IOException
    sample2 s = new sample2();
    s.checkThreadPoolExecutor();
    System.out.println("I am done with calling all threads- waiting for threads to finish");
    s.threadPoolExecutor.shutdown();
    try {
    while (!s.threadPoolExecutor.awaitTermination(1000L, TimeUnit.MILLISECONDS)) {
    // awaiting termination of all the threads here.
    catch(Exception e)
    System.out.println("Exception while waiting fot threads to finish");
    s.threadPoolExecutor.shutdown();
    System.out.println("Bye bye");
    public class TestThread implements Callable<Integer>
    int i =0;
    String sample = null;
    public TestThread(int i)
    this.i = i;
    @Override
    public Integer call() {
    System.out.println("I am thread-"+i + "and sleeping for 1 min");
    try
    Thread.sleep(1000*5);
    catch(InterruptedException ie)
    System.out.println("some one woke me up");
    try{
    String test = sample.substring(0,1);
    catch(Exception e)
    throw new RuntimeException(e);
    return i;
    private void checkThreadPoolExecutor()
    for(int i = 0; i <10;i++)
    testMethod(i);
    System.out.println("I am done with i:" + i + " in checkThreadPoolExec");
    private void testMethod(int i)
    TestThread thread = new TestThread(i);
    Future<Integer> future = threadPoolExecutor.submit(thread);
    Edited by: Pallavi.Palleti on Feb 17, 2009 7:41 PM

    Hi,
    some hints for future postings:
    - use code-tags when submitting code (tags are available at icon bar at the top of your message editor); this will make your code easier to read given you preserved proper indentation when copying it to your posting
    - class names should start with an upper case letter (e.g. "public class Sample2" instead of "public class sample")
    - you do not submit "Threads" to an executor, you either submit Runnables or Callables; Threads are pooled inside the executor to execute the Runnables/Callables you submit
    As for your question: where exactly do you want to handle the exception? Within your Runnable or when checking the result of the Future? For the second case, Future.get() should throw an ExecutionException if the underlying Runnable/Callable threw an exception.
    In general, there is the concept of an UncaughtExceptionHandler that will take care of any execptions that occur and have not been handled by the corresponding implementation.
    Bye.

  • 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

  • Throwing exceptions in threads

    I made a thread class that uses a BufferedReader object wrapped in a InputStream and Socket object inside the run() method that uses the command this.input.readline().
    The only problem is that in order to use this method, I need to throw java.io.IOException. When I try and do this, it says:
    "The method void run() declared in class InputThread cannot overide the method of the same signature declared in class java.land.Thread. Their throws clauses are incompatible."
    Here is my original code:
    class InputThread extends Thread {
         BufferedReader input;
         public InputThread(BufferedReader input) {
              this.input = input;
         public void run() {
              String intext = "";
              while (true) {
                   intext = this.input.readLine();
                   if (intext != "") {
                        System.out.println("Thread received: " + intext);
    }How can I still use the this.input.readLine() function in the InputThread class?
    (I already tried "public void run() throws java.io.IOException {")
    Thanks!

    The run method should handle all exceptionn that could occur in the
    contained code. There's als no point in propagating a (checked) exception
    to a higher level by wrapping it in an unchecked exception like RuntimeException
    which is not commited to be declared in the throws clause.
    So ...
    public void run() {   
       try {
       } catch (Exception ex) {
          throw new RuntimeException("bla", ex);
    } ...would compile. BUT where would you catch the exception??? Don't be mistaken,
    but the exception is never propagated to the code that started the thread!!!
    Threads are the end points for exceptions because they run parallel to other code.
    In my opinion the best and most correct code would be:
    class InputThread extends Thread {
         BufferedReader input;
         public InputThread(BufferedReader input) {
              this.input = input;
         public void run() {
              String intext = "";
              try {
                  while (true) {
                   intext = this.input.readLine();
                   if (intext != "") {
                        System.out.println("Thread received: " + intext);
                    } catch (IOEXception ex) {
                        // log exception and die gracefully
    }

  • Accessing shared database throws exception from one of 2 web roles

    Setup:
    Shared database
    Main site and "admin site" each using separate web roles accessing shared database.
    I had things working and running correctly until about 2 days ago.  Then, only the "admin site" stopped working.  I am using the same code to access the database across both sites but am getting the following exception when trying to access the
    database in the admin site:
    Message: Unable to open connection to "Microsoft SQL Server, provider V2.0.0.0 in framework .NET V2.0".
    Stack Trace: at IBatisNet.DataMapper.SqlMapSession.OpenConnection(String connectionString) at IBatisNet.DataMapper.SqlMapSession.OpenConnection() at IBatisNet.DataMapper.Commands.DbCommandDecorator.System.Data.IDbCommand.ExecuteReader() at IBatisNet.DataMapper.MappedStatements.MappedStatement.RunQueryForObject[T](RequestScope
    request, ISqlMapSession session, Object parameterObject, T resultObject) at IBatisNet.DataMapper.MappedStatements.MappedStatement.ExecuteQueryForObject[T](ISqlMapSession session, Object parameterObject, T resultObject) at IBatisNet.DataMapper.MappedStatements.MappedStatement.ExecuteQueryForObject[T](ISqlMapSession
    session, Object parameterObject) at IBatisNet.DataMapper.SqlMapper.QueryForObject[T](String statementName, Object parameterObject) at AutoOffers.Persistence.SqlMapperWrapper.QueryForObject[T](String statementName, Object parameter) at AutoOffers.Persistence.Mappers.DbUserMapper.FindByEmailAddress(String
    emailAddress) at AutoOffers.Persistence.Repositories.UserRepository.FindByEmailAddress(String emailAddress) at AutoOffers.Core.Domain.Services.Authentication.MembershipService.ValidateUser(String username, String password) at Admin.AutoOffers.Web.Controllers.HomeController.Login(LoginModel
    model, String returnUrl) at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,
    IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
    at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
    asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
    at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult
    asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult
    asyncResult)
    NOTE: I've tried to go to the v4 provider but get the same error (except with v4 in place of v4).  I would suspect something amiss with my application if I didn't have a working one using shared code...though I'm still not ruling out that I'm doing
    something wrong, just waiting for input from here.
    Thanks in advance.

    Hey there, and apologies for the lack of response.  Are you still having this issue and still needing help?  If so can you tell me a little more.  Where is the application running (web/worker rolls)? what are the details on the SQL Database?
    Thanks Guy

  • Cannot throw exception from switch-"unreachable statement"

    Hi,
    why is this an unreachable statement?
      public static Msg newMsg(int type, Object data)
          Msg msg;
          switch (type)
              case MsgTypes.MSG_CLUSTER_CREATED:
                  msg=new MsgClusterCreated(); break;
              case MsgTypes.MSG_REPLY:
                  msg=new MsgReply(); break;
              default:
                  throw new MessageTypeNotDeclaredException(); break;     //unreachable statement!!!        
          msg.setDataSegment(data);
          return msg;
      }

    When you throw an exception, the program flow never continues "normally" on the next line --- control is always transferred to the nearest exception handler. Thus control never reaches the break statement on the same line, and "unreachable statements" like this are illegal in Java.
    Solution: remove the unnecessary "break;"

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

Maybe you are looking for

  • How do I watch a movie from my I pad to my Apple TV

    I want to watch a movie from my iPad and put it on my tv through Apple TV. How do I do this? I found the air play on Apple TV but there is nothing on my I pad. Thank you

  • Possible fix for problems with Location Services!!!!

    Alright, I had just bought a brand new iPod Touch 5th Generation and was having trouble with any app that used Location services (Siri, Weather, Maps, etc) and it was driving me absolutely crazy. Now, I live in a very VERY rural area in Pennsylvania

  • Guys i m nt able to download ios5 it coming tht tht the request has timed out ?

    guys i m nt able to download ios 5 i dont knw. on the other hand my iphone 4 is frm uk it wsa vodafone locked wen i came to mumbai i hd it factory unlockd nd nw i m scared tht as soon i upgrade it nto ios 5        it will get locked again wht shud i

  • How to Schedule Multiple projects

    Hi All, I hav a scenario in which there are almost 50 projects live in the system and suddenly 2 new projects come up which are to be taken at priority no.2 & 3 w.r.t the 50 present. These two projects would be consuming the existing resources. Is th

  • How i can change my email ID here

    How I can change my email ID here, coz i bought another iphone but im using the same Email and i have trouble when i change my password from the other phone my contacts was transfered to another one or vice versa. and I received messages from my othe