這是一個介紹基本異常處理的小例子,包括拋出,捕獲,斷言,日志。
Java異常處理通過5個關(guān)鍵字try、catch、throw、throws、finally進行管理。基本過程是用try語句塊包住要監(jiān)視的語句,如果在try語句塊內(nèi)出現(xiàn)異常,則異常會被拋出,你的代碼在catch語句塊中可以捕獲到這個異常并做處理;還有以部分系統(tǒng)生成的異常在Java運行時自動拋出。你也可以通過throws關(guān)鍵字在方法上聲明該方法要拋出異常,然后在方法內(nèi)部通過throw拋出異常對象。
package com.hongyuan.test;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ExceptionHandleTest {
static{
//開啟斷言,此后由系統(tǒng)類加載器加載的類將啟用斷言。
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
}
public static void main(String[] args) {
/*
* 拋出,捕獲
*/
try {
TryCatchTest.run(10, -1);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("====================================================");
//日志
LogerTest.run();
System.out.println("====================================================");
//斷言
AssertTest.div(3,0);
}
}
/*
* 斷言
*/
class AssertTest {
public static double div(int b,int a){
assert a!=0:"你這么用,你小學(xué)老師知道嗎?";
return (double)b/a;
}
}
/*
* 日志
*/
class LogerTest {
private static Logger logger=null;
static{
//獲取日志對象并定義日志級別
logger=Logger.getLogger(LogerTest.class.getName());
logger.setLevel(Level.ALL);
}
public static void run(){
//進入方法
logger.entering(LogerTest.class.getName(), "run");
//普通信息
logger.info("又來找我麻煩,這筆賬我記下了!!!");
//警告
logger.warning("太累了,這活沒法干了!!!");
//嚴重
logger.log(Level.SEVERE,"老子不干了!!! ^O^");
//退出方法
logger.exiting(LogerTest.class.getName(), "run");
}
}
/*
* 捕獲,拋出
*/
class TryCatchTest {
public static void run(int x,int y) throws IOException {
try{//必須
if(x<0||y<0){
throw new IllegalArgumentException("無語了,這讓我怎么辦啊!!!");
}
}catch(Exception e){//可選
IOException e1=new IOException("你自己看著辦吧!");
e1.initCause(e.getCause());
throw e1;
}finally{//可選
System.out.println("最后他們過上了幸福的生活!!!!(完)");
}
}
}