This is a small example that introduces basic exception handling, including throwing, capturing, asserting, and logging.
Java exception handling is managed through 5 keyword try, catch, throw, throws, finally. The basic procedure is to wrap the statement you want to monitor with a try statement block. If an exception occurs within a try statement block, the exception is thrown, and your code catches the exception in the catch statement block and handles it, and the exception that is generated by some system is automatically thrown in the Java runtime. You can also declare the method to throw an exception by using the throws keyword, and then throw the exception object through throw inside the method.
Copy 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{
The assertion is turned on, and the class that is loaded by the System class loader will enable the assertion thereafter.
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);
}
}
/*
* Assert
*/
Class Asserttest {
public static double div (int b,int a) {
Assert a!=0: "You so use, your elementary school teacher know?" ";
Return (double) b/a;
}
}
/*
* log
*/
class Logertest {
private static Logger logger=null;
The
static{
//Gets the log object and defines 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 me again, I got this account, I wrote it down!!! ");
//warning
logger.warning ("Too tired to 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{//must
if (x<0| | y<0) {
throw new IllegalArgumentException ("No words, this let me do AH!!!" ");
}
}catch (Exception e) {//optional
IOException e1=new IOException ("You can do it yourself!");
E1.initcause (E.getcause ());
Throw E1;
}finally{//Optional
System.out.println ("In the end they live a happy life!!!! (end) ");
}
}
}