This is a small example that introduces basic exception handling, including throwing, catching, asserting, and logging.
Java exception handling is managed through five keywords: try, catch, throw, throws, and finally. The basic process is to wrap the statement to be monitored with a try statement block. If an exception occurs within the try statement block, the exception will be thrown. Your code can capture the exception and handle it in the catch statement block; and the following Some system-generated exceptions are automatically thrown when Java is running. You can also declare the method to throw an exception through the throws keyword, and then throw the exception object through throw inside the method.
Copy the code code as follows:
package com.hongyuan.test;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ExceptionHandleTest {
static{
//Enable assertions, and classes loaded by the system class loader will have assertions enabled.
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
}
public static void main(String[] args) {
/*
* Throw, catch
*/
try {
TryCatchTest.run(10, -1);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("============================================ =========");
//log
LogerTest.run();
System.out.println("============================================ =========");
//assertion
AssertTest.div(3,0);
}
}
/*
* assertion
*/
class AssertTest {
public static double div(int b,int a){
assert a!=0: "Does your primary school teacher know if you use this?";
return (double)b/a;
}
}
/*
* log
*/
class LogerTest {
private static Logger logger=null;
static{
//Get the log object and define the log level
logger=Logger.getLogger(LogerTest.class.getName());
logger.setLevel(Level.ALL);
}
public static void run(){
//Enter method
logger.entering(LogerTest.class.getName(), "run");
//General information
logger.info("Come to trouble me again, I have recorded this account!!!");
//warn
logger.warning("I'm too tired, I can't do this job!!!");
//serious
logger.log(Level.SEVERE,"I quit!!!^O^");
//Exit method
logger.exiting(LogerTest.class.getName(), "run");
}
}
/*
* capture, throw
*/
class TryCatchTest {
public static void run(int x,int y) throws IOException {
try{//required
if(x<0||y<0){
throw new IllegalArgumentException("I'm speechless, what should I do!!!");
}
}catch(Exception e){//optional
IOException e1=new IOException("You can figure it out yourself!");
e1.initCause(e.getCause());
throw e1;
}finally{//optional
System.out.println("Finally they lived a happy life!!! (End)");
}
}
}