How to implement top level exception handling?

前端 未结 5 1211
再見小時候
再見小時候 2020-12-31 17:19

I recently had to develop an additional module for an existing service developed by a colleague. He had placed a try/catch block in the main working function for catching al

5条回答
  •  失恋的感觉
    2020-12-31 18:01

    In any Java application, you just about always want to define an exception handler for uncaught exceptions with something like this:

    Thread.setDefaultUncaughtExceptionHandler( ... );
    

    where the object that will catch these uncaught exceptions will at least log the failure so you have a chance to know about it. Otherwise, there is no guarantee that you'll even be notified that a Thread took an Exception -- not unless it's your main Thread.

    In addition to doing this, most of my threads have a try/catch where I'll catch RunnableException (but not Error) and log it ... some Threads will die when this happens, others will log and ignore, others will display a complaint to the user and let the user decide, depending on the needs of the Application. This try/catch is at the very root of the Thread, in the Runnable.run() method or equivalent. Since the try/catch is at the root of the Thread, there's no need to sometimes disable this catch.

    When I write in C#, I code similarly. But this all depends on the need of the application. Is the Exception one that will corrupt data? Well then, don't catch and ignore it. ALWAYS log it, but then Let the application die. Most Exceptions are not of this sort, however.

提交回复
热议问题