码迷,mamicode.com
首页 > 其他好文 > 详细

e1084. 捕获错误和异常

时间:2018-09-02 21:44:48      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:from   class   false   app   col   rms   end   ica   api   

All errors and exceptions extend from Throwable. By catching Throwable, it is possible to handle all unexpected conditions.

There are several scenarios where it is good practice to catch Throwable. For example, in a server application, the threads that handle requests should catch Throwable and relay any errors or exceptions to the client. Another scenario is a long-running thread that performs some background activity. Such threads should catch Throwable, log any errors or exceptions, and then continue functioning.

It is rarely good practice for a method in a library to catch Throwable. In general, errors and exceptions should not be masked from the caller.

This example demonstrates a long-running thread that catches Throwable and logs the exception.

    class BgThread extends Thread {
        // Create a logger. For more information on the logging api‘s,
        // see e385 一个精简的日志记录程序
        Logger logger = Logger.getLogger("com.mycompany.mypackage");
    
        BgThread() {
            // As a daemon thread, this thread won‘t prevent the application from exiting
            setDaemon(true);
        }
    
        // Set to true to shut down this thread
        boolean stop = false;
    
        public void run() {
            while (!stop) {
                try {
                    // Perform work here
                } catch (Throwable t) {
                    // Log the exception and continue
                    logger.log(Level.SEVERE, "Unexception exception", t);
                }
            }
        }
    }

e1084. 捕获错误和异常

标签:from   class   false   app   col   rms   end   ica   api   

原文地址:https://www.cnblogs.com/borter/p/9575280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!