e388. logging an exception.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 34 行

TXT
34
字号
The logger method log() can be used to log an exception. Also, the convenience method Logger.throwing() can be used by a method about to throw an exception. 
    package com.mycompany;
    class MyClass {
        public void myMethod() {
            Logger logger = Logger.getLogger("com.mycompany.MyClass");
    
            // This method should be used when an exception is encounted
            try {
                // Test with an exception
                throw new IOException();
            } catch (Throwable e){
                // Log the exception
                logger.log(Level.SEVERE, "Uncaught exception", e);
            }
    
            // When a method is throwing an exception, this method should be used
            Exception ex = new IllegalStateException();
            logger.throwing(this.getClass().getName(), "myMethod", ex);
        }
    }

Here is a sample of the output generated by the example: 
    Jan 11, 2002 5:16:49 PM com.mycompany.MyClass myMethod
    SEVERE: Uncaught exception
    java.io.IOException
            at com.mycompany.MyClass.myMethod(com.mycompany.MyClass.java:32)
            at com.mycompany.MyClass.main(com.mycompany.MyClass.java:18)
    Jan 11, 2002 5:16:50 PM com.mycompany.MyClass myMethod
    FINER: THROW
    java.lang.IllegalStateException
            at com.mycompany.MyClass.myMethod(com.mycompany.MyClass.java:25)
            at com.mycompany.MyClass.main(com.mycompany.MyClass.java:18)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?