Trying to catch all exceptions...

Hi, developers!
I am trying to develop the best code, that can catch all the exceptions, in the best possible way, and whenever as possible it must register in a log with informations about the exception occurred.
I need your suggestions. See the code below:
MyClass()
  throws IOException, MyException {
  Throwable objThrowable1 = null;
  try {
    doSomething();
  } catch(MyException e) {
    objThrowable1 = e;
    throw e;
  } catch(IOException e) {
    objThrowable1 = e;
    throw e;
  } catch(RuntimeException e) {
    objThrowable1 = e;
    throw e;
  } catch(Exception e) {
    objThrowable1 = e;
    throw new Exception("Some Exception occurred.", e);
  } catch(Error e) {
    objThrowable1 = e;
    throw e;
  } finally {
    if (objThrowable1 != null) {
      Throwable objThrowable2 = null;
      try {
        log.fatal(objThrowable1);
        objThrowable1.printStackTrace();
      } catch(RuntimeException e) {
        objThrowable2 = e;
        throw e;
      } catch(Exception e) {
        objThrowable2 = e;
        throw new Exception("Some Exception occurred while logging.", e);
      } catch(Error e) {
        objThrowable2 = e;
        throw e;
      } finally {
        if (objThrowable2 != null) {
          objThrowable2.printStackTrace();
}It is the constructor of MyClass, and it might throw IOException or MyException.
Now some questions:
1) Do you think I exaggerated and wrote a lot of code, more than sufficient?
2) I wrote all this code because I think it�s a good idea throwing exceptions, especially RuntimeException and Error. The Virtual Machine must know how to handle the situation when some exception occurs. But I want to register a log of the exception, too, whenever as possible. In my opinion, the only way to advise the Virtual Machine that some exception occurred is throwing this exception. Do you agree? Do I really need to worry about it?
Thanks in advance!

Hi, developers!
I am trying to develop the best code, that can catch
all the exceptions, in the best possible way,Define "best possible way". I don't think what you're proposing is even close, by any measure.
You should only catch exceptions that you intend to handle. If there's no way for your class to handle the exception, it should bubble it up to the class that will. Catching and rethrowing like that seems a total waste to me.
I need your suggestions. See the code below:I'd suggest that this is an ugly mess. I would not go this way.
I have no idea whatsoever about that finally block. That should be for cleanup. What are you doing there?
MyClass()
throws IOException, MyException {
Throwable objThrowable1 = null;
try {
doSomething();
} catch(MyException e) {
objThrowable1 = e;
throw e;
} catch(IOException e) {
objThrowable1 = e;
throw e;
} catch(RuntimeException e) {
objThrowable1 = e;
throw e;
} catch(Exception e) {
objThrowable1 = e;
throw new Exception("Some Exception occurred.",
d.", e);
} catch(Error e) {
objThrowable1 = e;
throw e;
} finally {
if (objThrowable1 != null) {
Throwable objThrowable2 = null;
try {
log.fatal(objThrowable1);
objThrowable1.printStackTrace();
} catch(RuntimeException e) {
objThrowable2 = e;
throw e;
} catch(Exception e) {
objThrowable2 = e;
throw new Exception("Some Exception occurred
occurred while logging.", e);
} catch(Error e) {
objThrowable2 = e;
throw e;
} finally {
if (objThrowable2 != null) {
objThrowable2.printStackTrace();
}It is the constructor of MyClass, and it might
throw IOException or MyException.
Now some questions:
1) Do you think I exaggerated and wrote a lot of
code, more than sufficient?
2) I wrote all this code because I think it�s a good
idea throwing exceptions, especially
RuntimeException and Error. The Virtual
Machine must know how to handle the situation when
some exception occurs. But I want to register a log
of the exception, too, whenever as possible. In my
opinion, the only way to advise the Virtual Machine
that some exception occurred is throwing this
exception. Do you agree? Do I really need to worry
about it?
Thanks in advance!Cath t

Similar Messages

  • Best Practice: JavaFX pattern for "Catching all Exceptions"

    Hi,
    what is on the current JavaFX Standard the best way to catch all Exceptions (centralized) within my JavaFX application...
    I read thread outside this Oracle Forum who recommend following:
    1. Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
    --> catch all runtime exceptions
    2. http://stackoverflow.com/questions/12318861/javafx-2-catching-all-runtime-exceptions
    --> Implementing some source code who wrap the current GUI thread...
    3. I read something like:
    "JavaFX exception handling is almost identical to that in Java, apart from the fact that checked exceptions are handled in the same way as unchecked exceptions. This is good news for most Java programmers moving to JavaFX because you are no longer obliged to catch and handle exceptions."
    Sounds very good! But where/how can I do this ???
    Edited by: wschele on 19.02.2013 04:58
    Edited by: wschele on 19.02.2013 05:16

    No recommendation whats the best way to do it?
    Catching each Exception in different layers is boring ! :-(

  • Best way to catch all exceptions

    What is the best way to proceed if I would like to catch all exceptions in my Swing app?
    If there is an unexpected RuntimeException in my app, I would like to display an error message rather than having the program react silently. Is there a good way of making sure all uncaught exceptions are trapped and reported somewhere in the end? And are there any special inconveniences to such a strategy?

    A very similar question was asked recently. Various solutions were proposed in [this topic|http://forums.sun.com/thread.jspa?forumID=57&threadID=5416873] .

  • A catch-all "exception handler" - what's the end of an stack trace?

    I've created an application that is beeing tested these days, and I thought it would be a good idea to implement a "catch-all" exception handler so that I could notify the user when an exception occur (so that he may stop, send me the log, and to prevent errors that occur as a result of the first one).
    The way I've started implementing it is I redirect error out to a custom output stream:
    public class ConsoleOutStream extends ByteArrayOutputStream {
        private JFrame owner;
        public ConsoleOutStream(JFrame owner) {
            this.owner = owner;
         * Writes <code>len</code> bytes from the specified byte array
         * starting at offset <code>off</code> to this byte array output stream.
         * @param   b     the data.
         * @param   off   the start offset in the data.
         * @param   len   the number of bytes to write.
        public synchronized void write(byte b[], int off, int len) {
            super.write(b, off, len);
            checkForExceptions();
         * Writes the specified byte to this byte array output stream.
         * @param   b   the byte to be written.
        public synchronized void write(int b) {
            super.write(b);
            checkForExceptions();
        private void checkForExceptions() {
            reset();
            if(this.toString().indexOf("xception") != -1) {
                System.out.println("Exception!!\n\n");
                System.out.println(this.toString());
    }then i redirect System.err:
    PrintStream out = new PrintStream(new ConsoleOutStream(this));
    System.setErr(out);
    The problem is that the checkForExceptions() method will be called, e.g. 3 times for each exception - and I just want to display an error message to the user once (of course).
    Anyone done something similar?

    I'm interested in catching all "unhandled errors"how about:
    public static void main(String[] args){
        try{
        //whatever you would normally call from main
        }catch (Throwable e){
             System.out.println("There was an unhandled exception:");
             e.printStackTrace();
    }

  • How to catch ALL Exception in ONE TIME

    I'm explain my issue:
    I'm making a program with Class, Swing, Thread ...
    Then all action I do on my graphical application, I use a new thread, well
    I want to capture in my Startup programs, all unknow exception and then, I display it with a JOptionPane for example
    In fact, I want to do something like Eclipse, when it crash, I capture the error
    Could you help me ? Tell me the best way to do that ?
    This is an exemple
    FILE: Startup.java
    class Startup{
    public static main (String args[]){
    try{
    new Main();
    }catch(Throwable e){
    //Message d'erreur fenetre
    FILE: Main.java
    class Main{
    Main(){
    init_action();
    void init_action(){
    mybutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    Thread th=new Thread(){
    public void run(){
    int a = 1 / 0;
    th.start();
    Well, in this example I want to capture the Divide By 0, I use the Throwable Exeption, in order to be sure I catch all unknow exeption
    Then, a good job, is to put throws Throwable in all function
    but Thread, and ActionPerformed ... could not implement it
    How to put this exception and jump it to Startup Program ?

    I already do that, what can I do for improving capture ?
    That's impossible ... It will be a great idea to make a Redirection of Error to a Exception class in futur version
    For example, when an unknow error arrive, don't show it on console and crash ... but run a class redirector exception, and magic, it show you a beautiful error warning, and stop properly the programme ...
    I put an error class, and put try {] catch {} everywhere, and run my exception class,
    this class detect the error exception and run a properly beautiful and clear french message (I'm french :d)
    Well, If you have the BEST other idea, tell me, I read your message with a lot of regard
    see you soon
    bye

  • Catch All Exception

    Hi,
    I'm quite familiar with Oracle SOA, OSB , CEP stuff. Just exploring BPM and here i have a question on error handling.
    I see we can catch all system or business exceptions using a event sub process. and handle it. But i see no means to see what the error message is?
    Lets say i would like to email admin with the error message, from where can i retrieve the error message from?
    Any pointers on this is much appreciated.
    Thanks,
    Prakash

    I think you can use Error Events (Component Palette, from the Catch Events section select Error Event) and then log it or email it .
    Ref- 19.5 Handling Exceptions in a Business Process
    http://docs.oracle.com/cd/E21764_01/doc.1111/e15176/errors_bpmpd.htm
    Thanks
    Rupesh

  • Problems trying to catch custom exception.

    I am working out of Murach's Java SE 6 and doing one of the excersices. It says to Add a statement to Method3 of CustomTesterApp that throws a TestException without a message. I am getting a CustomTesterApp.java:26: <identifier> expected catch (TestException) error on compile. Here are the two classes. Thanks in advance for any help.
    TestException class
    import java.io.*;
    public class TestException extends Exception
         public TestException(){}
         public TestException(String message)
              super(message);
    CustomTesterApp
    import java.io.*;
    public class CustomTesterApp
        public static void main(String[] args)
            System.out.println("In main: calling Method1.");
            Method1();
            System.out.println("In main: returned from Method1.");
        public static void Method1()
            System.out.println("\tIn Method1: calling Method2.");
            Method2();
            System.out.println("\tIn Method1: returned from Method2.");
        public static void Method2()
            System.out.println("\t\tIn Method2: calling Method3.");
            try
            Method3();
              catch (TestException)
                   System.out.println("TestException caught.");
            System.out.println("\t\tIn Method2: returned from Method3.");
        public static void Method3()
            System.out.println("\t\t\tIn Method3: Entering.");
              throw new TestException();
            //System.out.println("\t\t\tIn Method3: Exiting.");
    }

    That helped a bunch. Also had to modify Method 2. Here is the revised code that works. Thanks for the help.
    import java.io.*;
    public class CustomTesterApp
        public static void main(String[] args)
            System.out.println("In main: calling Method1.");
            Method1();
            System.out.println("In main: returned from Method1.");
        public static void Method1()
            System.out.println("\tIn Method1: calling Method2.");
            Method2();
            System.out.println("\tIn Method1: returned from Method2.");
        public static void Method2()
            System.out.println("\t\tIn Method2: calling Method3.");
            try
            Method3();
              catch (TestException e)
                   System.out.println("TestException caught.");
            System.out.println("\t\tIn Method2: returned from Method3.");
        public static void Method3() throws TestException
            System.out.println("\t\t\tIn Method3: Entering.");
              throw new TestException();
            //System.out.println("\t\t\tIn Method3: Exiting.");
    }

  • 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

  • Catching all the exceptions at once

    Can we catch all exception and throw it all at once?
    Here's what i want to do..
    Say i have a class in which i have around 4 sql statements
    which i'm putting it in a try. I do not want to throw execptions one by one.
    instead
    try{
    some statements
    catch{
    goto Error -->
    catch{
    goto Error -->
    Error:
    Show all the statements here..
    I do not want to do this manually..is there already an exists9ing class or something that we need to implement. Please reply
    Tahnks,
    Anjana

    Just catch Exception. its the motherclass of all exceptions.
    put everything in one big try/catch.

  • Catching all errors

    Hi
    is there a way to catch all errors, I know you can do try and
    catch fro your code
    about how about errors that come from built in Flex component
    I am trying to catch all errors and show it to the user in
    better format
    but most important, it seems flex will be frozen and you can
    do anything if the error is not caught and the only way around it
    to restart your browser
    Please help
    Thanks
    Kasem

    Everything I read suggests that this isn't possible in Flex.
    It seems that uncaught exceptions are handled by the Flash player.
    This link discusses the problem in Flex 1.5 and it notes the
    problem is not fixed in Flex 2.
    http://www.mail-archive.com/[email protected]/msg25874.html
    I'm going to continue to look. I really can't imagine that
    Adobe spent all that time reworking Flex and didn't address this
    problem.

  • Catching Runtime Exception

    Is it good practice to catch High level Exception in the try block, this would also catch RuntimeException. My personal opinion is not to catch the Runtime Exception and let the JVM handle it. However if there is a need to catch specific Runtime Exception, code should be written for that.
    try
    // Your code
    catch (Exception e)
    e.printStackTrace()
    }

    I agree that runtime exceptions should generally not
    be caught as they are mistakes of programmers.
    But in order to debug a large project with hundreds of
    classes it can be useful to do that anyways.
    Any my big question is: how?
    I tried to wrap the content of the main method in a
    try / catch block hoping that I could catch all
    exceptions not handled somewhere else.
    But it didn't work.
    I manually threw some exceptions somewhere in my GUI
    and the main method wrapper didn't get them.
    But the VM did and printed the exception message.
    But I didn't want the VM to catch my exceptions. I
    wanted to catch them myself at the lowest possible
    point in my own classes.
    And I thought that was the main method.
    Can anyone help me?
    Thank you
    Matthias Klein
    P.S. please excuse my improvable english; it's not my
    mother tongue.AWT uses many different threads in your program that you never find out about unless something breaks. main(String arg[]) starts as the lowest possible point but, if you construct a Frame, Image, or certain other objects from the AWT package, AWT Threads automatically start over which you have little or no control.
    Overall, I don't think it's actually possible to catch the Runtime Exceptions out of these Threads. The best this you can do about them is prevent them from happening.

  • How to throw or catch sql exception for executeReader sql adapter

    Wcf sql adapter was created and executeReader was used.
    When an invalid sql statement was constructed and send it to wcf sql adapter, it will hanging there, and no response. No exception was catched even though send chape  was inside a catch block. How can I catch this kind of exception
    or throw this exception ? I need to give client an exception resposne.
    thanks
    Gary

    I used scope with exception handle which has Exception object type: "System.SystemException".
    I guess this type "System.SystemException" can catch any exception, including sql exception. Maybe I am wrong. I got error from window event:
    A message sent to adapter "WCF-Custom" on send port "WcfSendPort_SqlAdapterBinding_DalCore_Custom" with URI "mssql://shig-quad-2k3e1//DataSourceOne?" is suspended.
     Error details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.
    Server stack trace:
       at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
       at System.ServiceModel.Channels.ServiceChannel.EndRequest(IAsyncResult result)
    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at System.ServiceModel.Channels.IRequestChannel.EndRequest(IAsyncResult result)
       at Microsoft.BizTalk.Adapter.Wcf.Runtime.WcfClient`2.RequestCallback(IAsyncResult result)
     MessageId:  {B24EF5B8-298A-4D4F-AA98-5E639361A7DB}
     InstanceID: {F8924129-265B-4652-B20E-8D25F8F20A51}
    If  "System.SystemException" can't catch all exception, which type can catch all exception ? I want to catch all exception in this catch block.
    thanks
    Gary

  • Catcherror event "catch all system exceptions" is not catching subLanguageExecutionFault

    catcherror event "catch all system exceptions" is not catching subLanguageExecutionFault in BPM process

    hi rani,
    thanks for the response
    i supply all the connection details(gatewayhost, gatewayservice, programid, clinet, systemnumber, applicationhost, userid, password etc.) to the program which extends "JCoIDoc.Server".
    the program is taking care of all the connection establishment details.but still m facing the same problem.
    i have also confirmed that the user is a communication user, not a dialogue user.
    thanks
    pavan

  • My iphone 5 has nod sound at all except for with headphones the volume keys says ringer I tried to restart my device and I reset my settings but nothing seems to work it happend to me 2 days ago and yesterday the sound came back for 10 minutes and then go

    Hey guys I hope u can help me out, my new 3 months old 16g iPhone 5 has problem
    The sound don't work at all except for with headphones, the volume says ringer.
    I've tried restarting my device, reset my settings I even tried using a Q-tip in the headphone jack.
    Please help me out.
    And btw yesterday it worked for like 10 minutes and then got back to no sound.
    And this silent mode isn't on.

    it's a hardware issue
    https://www.google.dk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC4Q FjAA&url=https%3A%2F%2Fdiscussions.apple.com%2Fthread%2F1343532%3Fstart%3D315%26 tstart%3D0&ei=Wy1hUYiWDs3Y4QSzqIHAAw&usg=AFQjCNHLi5JBEWvjM6SHBge36Or-m1YMEw&sig2 =-By7BjriUmZPDpHDnY_ySw&bvm=bv.44770516,d.bGE
    more hits from the search
    https://www.google.dk/search?client=opera&q=iphone+stuck+in+headphone+mode&sourc eid=opera&ie=utf-8&oe=utf-8&channel=suggest

  • BPEL catch all block doesn't catch fault

    Hi,
    I have a catch all block in my BPEL process. One instance tried to write to the Oracle database without success throwing a fault which wasn't taken by BPEL's catch all. I see an error on invoke but it does not go to catch all block.
    Exception occured when binding was invoked. Exception occured during invocation of JCA binding: "JCA Binding execute of Reference operation 'merge' failed due to: DBWriteInteractionSpec Execute Failed Exception. merge failed. Descriptor name: [writeCountry.Country]. Caused by java.sql.SQLRecoverableException: No more data to read from socket. Please see the logs for the full DBAdapter logging output prior to this exception. This exception is considered retriable, likely due to a communication failure. Because the global transaction is rolling back the invoke must be retried in a new transaction, restarting from the place of the last transaction commit. To classify it as non-retriable instead add property nonRetriableErrorCodes with value "17410" to your deployment descriptor (i.e. weblogic-ra.xml). ". The invoked JCA adapter raised a resource exception. Please examine the above error message carefully to determine a resolution.
    Global retry rollback fault thrown.
    The current JTA transaction is aborting due to an user rollback fault being thrown. The upstream component should retry in a new JTA transaction upon catching this fault.
    This exception was caused by a global retry fault being thrown from downstream component. The user had directed the BPEL engine to roll back the current JTA transaction and retry within new JTA transactions for the specified number of times and retry interval.
    There is no action recommended.
    Ah, I have one more question, I have a BPEL process wich write to the database to the table X. Some time ago i extended the table X and add one more column. Why does BPEL lost all data in dbadapter and does not sygnalize any error when invoked adapter? Usually when I drop or alter table i get an error message. This time I see that the transformation which was before invoke to dbadapter was done correctly but I can see no data in invoke which should be written
    All environment is on 11.1.1.6, BPEL 2.0
    Edited by: 863909 on 2012-08-29 01:05

    Aye. My catch all block is defined for a parent scope. Just some arrors are not catch by catch all block (the same as for OutOfMemoryError for java - which will never be catched). I just wonder, because my red invoke activity in the EM sygnalizes error and throw error message but catch all block does not get it. Process stoped on error invoke and not go into catch all.
    Change table aspect. I don't have a problem, because i deleted old and implemented new adapter. It works. I just wonder why when I deleted an atribute (column) from DB I got en error and process stops, but when I extended a table, my process were runing to the end and was marked as finished completely. Something is wrong here, because adapter didnt write all data it should write. Process were going and was finished without throwing an error.
    Edited by: 863909 on 2012-08-29 04:14

Maybe you are looking for

  • Error In Report Designer

    Hi When I'm opening a view in report designer I'm getting the following error.Can anyone please help me with this.Its very urgent for me to sort this issue. <b>The report designer doesn't support the query drilldown. Key figure in static filter is no

  • Windows VISTA Boot Camp?

    Would it be possible to run MS Windows VIsta with Boot Camp? or we will be only able to Install XP SP2. Thanks!

  • How cat I speed up video "Share" from iMovie library in to .mov file?

    How cat I speed up video "Share" from iMovie library in to .mov file? I am converting ONLY 18 sec. long video, and it says 88 min. till its completeion. ??? I have over 1TB of free space and my mac specs are: Processor  2.2 GHz Intel Core 2 Duo Memor

  • ORA-01078 and LRM-00109 error

    Hi, I have installed Oracle 11g on SUSE Linux 10 successfully.But i dont know whether the database is running or not.When i try to access "Oracle Enterprise Manager", it says that network problem. But however when i ping the system, its giving proper

  • I dropped my phone in a cup of water this morning. What is the price to replace it?

    I dropped my phone in a cup of water this morning. What is the price to replace it?