Java Exceptions - Handling exceptions without try catch

前端 未结 4 1749
予麋鹿
予麋鹿 2020-12-24 03:35

In Java, we handle exceptions using try catch blocks. I know that I can write a try catch block like the one below to catch any exception thrown in a method.



        
相关标签:
4条回答
  • 2020-12-24 03:50

    you could wrap each method that can throw in a try catch

    or use the getStackTrace()

    catch (Throwable t) {
        StackTraceElement[] trace = t.getStackTrace();
        //trace[trace.length-1].getMethodName() should contain the method name inside the try
    }
    

    btw catching throwable in not recommended

    0 讨论(0)
  • 2020-12-24 03:59

    Show the friendly message from within the catch block.

    0 讨论(0)
  • 2020-12-24 04:10
    try {
       // do something
       methodWithException();
    }
    catch (Throwable t) {
       showMessage(t);
    }
    
    }//end business method
    
    private void showMessage(Throwable t){
      /* logging the stacktrace of exception
       * if it's a web application, you can handle the message in an Object: es in Struts you can use ActionError
       * if it's a desktop app, you can show a popup
       * etc., etc.
       */
    }
    
    0 讨论(0)
  • 2020-12-24 04:11

    By default, the JVM handles uncaught exceptions by printing the stack-trace to System.err stream. Java allows us to customize this behavior by providing our own routine which implements Thread.UncaughtExceptionHandler interface.

    Take a look at this blog article which I wrote sometime back which explains this in detail ( http://blog.yohanliyanage.com/2010/09/know-the-jvm-1-uncaught-exception-handler/ ).

    In summary, all you have to do is write your custom logic as below :

    public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
      public void uncaughtException(Thread t, Throwable e) {
         // Write the custom logic here
       }
    }
    

    And set it using any of the three options I have described in the above link. For example, you could do the following to set the default handler for the entire JVM (so any uncaught exception thrown will be handled by this handler).

    Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler() );
    
    0 讨论(0)
提交回复
热议问题