Exception Handling Notes

Exception handling
exception throws throw new IllegalAccessException{"something need to do"}
exception inherits Error (does not expect the application to process, such as memory exhaustion, etc.), Exception (checked exception and unchecked exception (belongs to RuntimeException subclass) )
The golden rule of exception handling "Throw early, catch later"
When overriding a method, he cannot throw more checked exceptions than in the parent class method declaration
Exception catch

try{dosomething();}
catch(Exceptionclass1 e){handler}
catch(Exceptionclass2 e){handler}
catch(Exceptionclass3 e){handler}

  

The catch statement is required to match from top to bottom, so the specific exception type must be placed first

try{dosomething();}
catch(Exceptionclass1 | Exceptionclass2 | Exceptionclass3 e){handler}

Requires the handler to only call methods common to all exception classes on exception variables.

try-with-resources statement

try(Scanner in = new Scanner(Path.get("usr/share/dict/words"));
        PrintWriter out = new PrintWriter("output.txt")){
            while(in.hasNext()){
                out.printlnn(in.next().toLowerCase);
            }
        }

It is required that the resources in try() must implement the AutoCloseable interface. This interface has a separate close method, which ensures that the close method will be called. At the same time, the resources are closed in the reverse order of initialization, that is, out, which is closed before in.

It is worth noting that the finally
clause should not contain the return value, because it will replace the return value in the try. Secondly, the finally clause must ensure that no exception occurs, otherwise the exception that occurs in the try will be covered by the finally exception.
Exception re-throw
requires changing the exception category, i.e. reporting a subsystem failure with a user-understandable exception.
Example:

try{
    doWork();
} catch (SQLException ex){
     throw  new ServletException("database error",ex); // Modify to a user-friendly exception 
    
    Throwable ex2 = new CruftyOldException("dataBase error" );
    ex2.initCause(ex); // When the constructor of the exception class has no parameters to save the cause of the exception, this method can be used to 
    throw ex2;
}

When catching, you can use Throwable couse = ex.getCasue(); to get the original exception

Assertions
Assertions are a common approach to defensive programming. The assertion mechanism allows you to add test conditions to your tests and automatically remove them in production code.

assert condition;
assert condition:expression;

Example: assert x>=0; when x is less than 0, an AssertionError exception will be thrown to
enable and disable assertions (plus -enableassertions or -ea)
java -ea MainClass

Logger
is used for logging, and the log management system will call Logger.getGlobal() to obtain the default logger

Logger.getGlobal().info("Opening file"+filename); // It will automatically add the time, the class name and method of the calling class 
Logger.global.setLevel(Level.OFF); the info method will not record the log, but the message will was created.

Log level SERVER, WARNING, INFO, CONFIG, FINE, FINER, FINEST By default, the first three levels of logs will be recorded, and the level of logging can be changed through setLevel.
When the log level is set to be more fine-grained than the INFO level, it is necessary to Change the configuration of the log processor, the default log processor will not output logs lower than INFO level

logger.entering(String classname,String methodName,Object[] params) // Put it in the first item of the method to record the input parameters of the method 
logger.exiting(String className,String methodName,Object result) // Put it in the method return In the front, the return parameter used to record the method 
void logp(Level L, String className, String methodName, String message) // The exact location of the calling class and calling method can be obtained more precisely

By editing the configuration file, you can change different properties of the logging system. The default configuration file is located in jre/lib/logging.properties.
If you need to use other configuration files, you need to set java.util.logging.config when starting your application. The file attribute is the location of the configuration file you specify

java -Djava.util.logging.config.file=configFile.MainClass

In order to record the FINE level log, you need to modify the default logger level and processor level in the configuration file. Or install your own processor bypassing the config file.

Logger logger = Logger.getLogger("com.mycompany.myapp");
logger.setLevel(LEVEL.FINE);
logger.setUserParentHandlers(false);
Handler handler = new ConsoleHandler();
handler.setLevel(LEVEL.FINE);
logger.addHandler(handler);

If you need to send logs elsewhere, the logging API provides FileHandler and SocketHandler for this

FileHandler handler = new FileHandler();
logger.addHandler(handler);

The record will be sent to the javan.log file in the user's home directory, where n is an integer to ensure the uniqueness of the log file

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324776263&siteId=291194637